if there is a dictionary:
dict={'a':'b'}
in python 3, i would like to convert this dictionary key to a string and its value to another string:
print(key)
key='a'
print(type(key))
str
print(value)
value='a'
print(type(value))
str
Some attempts:
str(dict.key()) # returns 'dict' object has no attribute 'key'
json.dump(dict) # returns {'a':'b'} in string, but hard to process
Any easy solution? Thank you!
Use dict.items()
:
You can use dict.items()
(dict.iteritems()
for python 2), it returns pairs of keys and values, and you can simply pick its first.
>>> d = { 'a': 'b' }
>>> key, value = list(d.items())[0]
>>> key
'a'
>>> value
'b'
I converted d.items()
to a list, and picked its 0
index, you can also convert it into an iterator, and pick its first using next
:
>>> key, value = next(iter(d.items()))
>>> key
'a'
>>> value
'b'
Use dict.keys()
and dict.values()
:
You can also use dict.keys()
to retrieve all of the dictionary keys, and pick its first key. And use dict.values()
to retrieve all of the dictionary values:
>>> key = list(d.keys())[0]
>>> key
'a'
>>> value = list(d.values())[0]
>>> value
'b'
Here, you can use next(iter(...))
too:
>>> key = next(iter(d.keys()))
>>> key
'a'
>>> value = next(iter(d.values()))
'b'
Ensure getting a str
:
The above methods don't ensure retrieving a string, they'll return whatever is the actual type of the key, and value. You can explicitly convert them to str
:
>>> d = {'some_key': 1}
>>> key, value = next((str(k), str(v)) for k, v in d.items())
>>> key
'some_key'
>>> value
'1'
>>> type(key)
<class 'str'>
>>> type(value)
<class 'str'>
Now, both key
, and value
are str
. Although actual value in dict was an int
.
Disclaimer: These methods will pick first key, value pair of dictionary if it has multiple key value pairs, and simply ignore others. And it will NOT work if the dictionary is empty. If you need a solution which simply fails if there are multiple values in the dictionary, @SylvainLeroux's answer is the one you should look for.
To have a solution with several keys in dict without any import I used the following light solution.
dict={'a':'b','c':'d'}
keys = "".join(list(dict.keys()))
values = "".join(list(dict.values()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With