Turn a dictionary into two lists, one for keys and the other for values?

18,742

Solution 1

You can use in Python 2.x:

keys = tel.keys()
values = tel.values()

Or something funky like:

(keys,values) = zip(*tel.iteritems())

And in Python 3.x:

keys = list(tel.keys())
values = list(tel.values())
(keys,values) = zip(*tel.items())

(as in 3.x, keys(), values() and items() return iterators)

Solution 2

In one step (Python 2.x):

keys, values = zip(*tel.iteritems())

Or in Python 3.x:

keys, values = zip(*tel.items())

Solution 3

keys = my_dict.keys()
vals = my_dict.values()
keys,values = zip(*my_dict.items())

Solution 4

k = tel.keys() # a list of the dict keys
v = tel.values() # a list of the dict values

Or

k, v = [], []
for key, value in tel.items():
    k.append(key)
    v.append(value)  
Share:
18,742

Related videos on Youtube

Admin
Author by

Admin

Updated on September 16, 2022

Comments

  • Admin
    Admin over 1 year

    I read in a object of type collections.defaultdict from a file using pickle.load. It has a numerical value for each string key. It seems to be just like an object of type dict, or I might be wrong.

    I would like to create two lists out of the object, one list consisting all the keys, and the other list all the values. How can I do that for an object of type dict? How can I do that for an object of type collections.defaultdict?

    For example, from an object of type dict

    tel = {'jack': 4098, 'sape': 4139}
    

    I would like to create two lists ['jack', 'sape'] and [4098, 4139].

    Thanks!!

    • Trent
      Trent about 10 years
      same order, or is the order of the two lists irrelevant?
  • Joran Beasley
    Joran Beasley about 10 years
    O i didnt know that went away in py3
  • isedev
    isedev about 10 years
    sorry tired... iterkeys() in 2.x = keys() in 3.x