I know about few of the questions answered here on SO about dict(list) i.e.
l = [['a',1] ['b',2]]
and do dict(l) then we get:
{'a': 1, 'b': 2}
But how to make a list with 2 elements
l = ['a',1]
become a dictionary such as:
{'a':1}
using the dict function?
dict expects an iterable of two-item iterables, so you will need to put l in a list:
>>> l = ['a',1]
>>> dict([l])
{'a': 1}
>>>
Note that you could also use a tuple:
>>> l = ['a',1]
>>> dict((l,))
{'a': 1}
>>>
This works for multiple elements in the list
>>> l = ['a',1,'b',2]
>>> i = [(l[i],l[i+1]) for i in range(0,len(l),2)]
>>> dict(i)
{'a': 1, 'b': 2}
For one element, dict([l]) would work. For multiple key/value pairs in a flattened list, you could use zip():
In [5]: l = ['a', 1, 'b', 2]
In [6]: dict(zip(l[::2], l[1::2]))
Out[6]: {'a': 1, 'b': 2}
Related
Say I have a a dictionary (e.g. d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}).
Say I want to read several keys of the dictionary, but not all (e.g. I want to read d['a'] and d['c']).
Here is the way I do it: (val_a, val_c) = (d[key] for key in ('a', 'c')).
Is there a more pythonic way to do this?
Use operator.itemgetter.
>>> from operator import itemgetter
>>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> get_ac = itemgetter('a', 'c')
>>> get_ac(d)
(1, 3)
Very similar to yours, but slightly shorter using map.
(Note: Just as with your approach, the result of map is not actually a tuple but a generator that is unpacked into multiple variables.)
>>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> a, c = map(d.get, ('a', 'c'))
>>> a, c
(1, 3)
I have a dictionary like such:
aDict = {'a': [1,2,3],
'b': [2,3,4],
'c': [3,3,6], ...}
How would I create a list that stores the maximum values at each index, (0,1,2).
Thanks!
If I understand right, you want something like this:
>>> aDict = {'a':[1,2,3],'b':[2,3,4],'c':[3,3,6]}
>>> aList = [max(aDict[k]) for k in sorted(aDict.keys())]
>>> print aList
[3, 4, 6]
Or maybe this:
>>> aDict = {'a':[1,2,3],'b':[2,3,4],'c':[3,3,6]}
>>> aDict2 = dict((k, max(aDict[k])) for k in aDict.keys())
>>> print aDict2
{'a': 3, 'c': 6, 'b': 4}
This question already has answers here:
Getting a list of values from a list of dicts
(10 answers)
Closed 7 years ago.
I have a list like this in python:
x = [{'A': 1, 'B': 2}, {'A': 3, 'B': 4}, {'A': 5, 'B': 6}]
that its members are Dictionary items. I want to filter the list to get this list:
X = [1, 3, 5]
is there some kind of magical command like x[0:2]['A'] to filter the list like this or not?
You can use list comprehension.
>>> y = [D['A'] for D in x]
>>> y
[1, 3, 5]
Also, as Vignesh Kalai pointed out, if you want this code to work even if the key isn't in the dictionary, use this instead:
[D.get('A') for D in x]
and then use list(filter(bool,y)) to take out the Nones. Like so:
>>> x = [{'A': 1, 'B': 2}, {'A': 3, 'B': 4}, {'A': 5, 'B': 6}, {'B': 8}]
>>> y = [D['A'] for D in x]
Traceback (most recent call last):
File "<pyshell#55>", line 1, in <module>
y = [D['A'] for D in x]
File "<pyshell#55>", line 1, in <listcomp>
y = [D['A'] for D in x]
KeyError: 'A'
>>> y = [D.get('A') for D in x]
>>> y
[1, 3, 5, None]
>>> y = list(filter(bool,y))
>>> y
[1, 3, 5]
There are so many ways to do this.
operator.itemgetter
If you happen to do this operation more often, then prefer this way
>>> from operator import itemgetter
>>> get_a = itemgetter('A')
>>> [get_a(item) for item in x]
[1, 3, 5]
Or with map
>>> list(map(get_a, x))
[1, 3, 5]
Simplest way to do this would be to use the [] operator, like this
>>> [item['A'] for item in X]
[1, 3, 5]
If you want to avoid the KeyError in dictionaries where A doesn't exist, you can use dict.get, which returns None by default, like this
>>> [item.get('A') for item in X]
[1, 3, 5]
I want to transform
l = ['a','b','c','d']
to
d = {'a': 0, 'b': 1, 'c': 2, 'd': 3}
The best solution I have so far is that one:
d = {l[i]:i for i in range(len(l))}
Is there more elegant way to do this?
d = {e:i for i, e in enumerate(l)}
Edit: As #LeonYoung suggested, if you want to be compatible with python < 2.7 (despite the tag), you must use
d = dict((e, i) for i, e in enumerate(l))
With itertools, just for fun
>>> from itertools import count, izip
>>> L = ['a', 'b', 'c', 'd']
>>> dict(izip(L, count()))
{'a': 0, 'c': 2, 'b': 1, 'd': 3}
If I have a dictionary
d = {'a':1, 'b':2 , 'c': 3}
with d['a'] or d.get('a') I get 1.
How can I get the values in the dictionary from a list of keys?
Something like
d[['a','b']]
Use list comprehension:
>>> d = {'a':1, 'b':2 , 'c': 3}
>>> [d[k] for k in ['a','b']]
[1, 2]
I would use map:
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> map(d.get, ['a','b'])
[1, 2]
Alternatively to a list in this case you could use a string. Like so:
map({'a':1, 'b':2 , 'c': 3}.get,"abc")