Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert every dictionary value to utf-8 (dictionary comprehension?)

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.

like image 709
PurpleVermont Avatar asked Nov 13 '15 18:11

PurpleVermont


People also ask

What is dictionary and list comprehension in Python?

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.

How do we fetch values from dictionary?

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.


2 Answers

Python 3 version building on that one answer by That1Guy.

{k: str(v).encode("utf-8") for k,v in mydict.items()}
like image 122
kjmerf Avatar answered Oct 24 '22 23:10

kjmerf


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.

like image 31
That1Guy Avatar answered Oct 24 '22 22:10

That1Guy