Return to Snippet

Revision: 26928
at May 17, 2010 06:33 by magicrebirth


Initial Code
# 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}

Initial URL

                                

Initial Description
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:

Initial Title
Dicts to Lists / Lists to Dicts

Initial Tags
list

Initial Language
Python