/ 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:
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:
Expand |
Embed | Plain Text
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}