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)
Related videos on Youtube
Author by
Admin
Updated on September 16, 2022Comments
-
Admin over 1 year
I read in a object of type
collections.defaultdict
from a file usingpickle.load
. It has a numerical value for each string key. It seems to be just like an object of typedict
, 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 typecollections.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 about 10 yearssame order, or is the order of the two lists irrelevant?
-
-
Joran Beasley about 10 yearsO i didnt know that went away in py3
-
isedev about 10 yearssorry tired... iterkeys() in 2.x = keys() in 3.x