I recently published a couple articles on data type conversions. If you would like to read them, here they are:
– String to Number Conversions
– Converting String Representations of Binary, Octal and Hexadecimal Integers
– Number to String Conversions
Today we’ll be talking about dictionary conversions. We’ll learn how to convert a dictionary to a string and to a list.
Here’s the video version of this article:
Dictionary to string
We can use the str function to convert a dictionary to a string:
>>> pets = {"Joe" : "bunny", "Mike" : "canary", "Steve" : "suslik"}
>>> pets_string = str(pets)
>>> pets_string
"{'Joe': 'bunny', 'Mike': 'canary', 'Steve': 'suslik'}"
>>> type(pets_string)
<class 'str'>
Dictionary to list
We can convert a dictionary to a list of 2-tuples. The keys become the first element in each tuple, the values – the second. We can do it by using the method items:
>>> prices = {"sugar" : 2.40, "milk" : 1.20, "oranges" : 2.80}
>>> price_items = prices.items()
The method items returns the so-called items view:
>>> price_items
dict_items([('sugar', 2.4), ('milk', 1.2), ('oranges', 2.8)])
You can learn more about dictionary views, so keys views, values views and items views, in this article.
You can then use the list method to convert the items view into a list:
>>> items = list(price_items)
>>> items
[('sugar', 2.4), ('milk', 1.2), ('oranges', 2.8)]
You can also create a list of just the keys. We need the method keys:
>>> price_keys = prices.keys()
Again, we get a keys view:
>>> price_keys
dict_keys(['sugar', 'milk', 'oranges'])
which can then be converted to a list:
>>> keys = list(price_keys)
>>> keys
['sugar', 'milk', 'oranges']
It works the same for the values. You can use the values method to create a list of just the values:
>>> price_values = prices.values()
First we get a values view:
>>> price_values
dict_values([2.4, 1.2, 2.8])
and then we can use the list method to convert it into a list:
>>> values = list(price_values)
>>> values
[2.4, 1.2, 2.8]