I have a dictionary and I want to convert every value to utf-8. This works, but is there a "more pythonic" way?
for key in row.keys():
row[key] = unicode(row[key]).encode("utf-8")
For a list I could do
[unicode(s).encode("utf-8") for s in row]
but I'm not sure how to do the equivalent thing for dictionaries.
This is different from Python Dictionary Comprehension because I'm not trying to create a dictionary from scratch, but from an existing dictionary. The solutions to the linked question do not show me how to loop through the key/value pairs in the existing dictionary in order to modify them into new k/v pairs for the new dictionary. The answer (already accepted) below shows how to do that and is much clearer to read/understand for someone who has a task similar to mine than the answers to the linked related question, which is more complex.
List comprehensions and dictionary comprehensions are a powerful substitute to for-loops and also lambda functions. Not only do list and dictionary comprehensions make code more concise and easier to read, they are also faster than traditional for-loops.
You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.
Python 3 version building on that one answer by That1Guy.
{k: str(v).encode("utf-8") for k,v in mydict.items()}
Use a dictionary comprehension. It looks like you're starting with a dictionary so:
mydict = {k: unicode(v).encode("utf-8") for k,v in mydict.iteritems()}
The example for dictionary comprehensions is near the end of the block in the link.
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