Dicts to Lists / Lists to Dicts


/ Published in: Python
Save to your folder(s)

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
  1. # dicts to lists
  2.  
  3. dictionary = {'a': 1, 'b': 2, 'c': 3}
  4. 2dict_as_list = dictionary.items()
  5. # dict_as_list now contains [('a', 1), ('b', 2), ('c', 3)]
  6.  
  7.  
  8. # lists to dicts
  9.  
  10. dict_as_list = [['a', 1], ['b', 2], ['c', 3]]
  11. dictionary = dict(dict_as_list)
  12. # dictionary now contains {'a': 1, 'b': 2, 'c': 3}
  13.  
  14. # You can also combine this with the 'keyword arguments' method of creating a dict
  15.  
  16. dict_as_list = [['a', 1], ['b', 2], ['c', 3]]
  17. dictionary = dict(dict_as_list, d=4, e=5)
  18. # dictionary now contains {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.