# Posted By

magicrebirth on 05/17/10

# Statistics

Viewed 466 times
Favorited by 0 user(s)

# Dicts to Lists / Lists to Dicts

/ Published in: Python

Turning a dictionary into a list or an iterator is easy. To get a list of keys, you can just cast the dict into a list. It's cleaner, though to call .keys() on the dictionary to get a list of the keys, or .iterkeys() to get an iterator. Similarly, you can call .values() or .itervalues() to get a list or iterator of dictionary values. Remember though, that dicts are inherently unordered and so these values won't be in any meaningful order.

To preserve both keys and values, you can turn a dict into a list or iterator of 2-item tuples by using .items() or .iteritems(). This is something that you'll probably do a lot, and isn't very exciting:

Copy this code and paste it in your HTML
`# dicts to lists dictionary = {'a': 1, 'b': 2, 'c': 3}2dict_as_list = dictionary.items()# dict_as_list now contains [('a', 1), ('b', 2), ('c', 3)]  # lists to dicts dict_as_list = [['a', 1], ['b', 2], ['c', 3]]dictionary = dict(dict_as_list)# dictionary now contains {'a': 1, 'b': 2, 'c': 3} # You can also combine this with the 'keyword arguments' method of creating a dict dict_as_list = [['a', 1], ['b', 2], ['c', 3]]dictionary = dict(dict_as_list, d=4, e=5)# dictionary now contains {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}`