This is the list in Python:
a = [{a:3,b:4}, {c:14,d:24}]
How can I create a list consisting only from the values of the dictionaries?
Like this:
a1=[3,4,14,24]
I have made this with a for loop, but is there an other way of doing this?
This is the list in Python:
a = [{a:3,b:4}, {c:14,d:24}]
How can I create a list consisting only from the values of the dictionaries?
Like this:
a1=[3,4,14,24]
I have made this with a for loop, but is there an other way of doing this?
Since the order apparently doesn't matter:
>>> a = [{'a':3,'b':4}, {'c':14,'d':24}]
>>> a
[{'a': 3, 'b': 4}, {'c': 14, 'd': 24}]
You can get the values in a listcomp:
>>> [d.values() for d in a]
[[3, 4], [14, 24]]
And then flatten this using a nested listcomp:
>>> [value for d in a for value in d.values()]
[3, 4, 14, 24]
which is equivalent to
>>> newlist = []
>>> for d in a:
... for value in d.values():
... newlist.append(value)
...
>>> newlist
[3, 4, 14, 24]
If you really don't even want the word for
in there, I guess you could use
>>> from itertools import chain
>>> list(chain(*map(dict.values, a)))
[3, 4, 14, 24]
[Update:]
Some performance comparisons (mostly for information's sake about the scaling at large N):
>>> a = [{'a':3,'b':4}, {'c':14,'d':24}]
>>>
>>> timeit [value for d in a for value in d.itervalues()]
1000000 loops, best of 3: 1.02 us per loop
>>> timeit [value for d in a for value in d.values()]
1000000 loops, best of 3: 1.32 us per loop
>>> timeit list(chain(*map(dict.values, a)))
100000 loops, best of 3: 4.45 us per loop
>>> timeit reduce(operator.add, (d.values() for d in a))
100000 loops, best of 3: 2.01 us per loop
>>> timeit sum((d.values() for d in a), [])
100000 loops, best of 3: 2.08 us per loop
>>>
>>> a = [{'a':3,'b':4}, {'c':14,'d':24}] * 1000
>>>
>>> timeit [value for d in a for value in d.itervalues()]
1000 loops, best of 3: 612 us per loop
>>> timeit [value for d in a for value in d.values()]
1000 loops, best of 3: 915 us per loop
>>> timeit list(chain(*map(dict.values, a)))
1000 loops, best of 3: 1.07 ms per loop
>>> timeit reduce(operator.add, (d.values() for d in a))
100 loops, best of 3: 17.1 ms per loop
>>> timeit sum((d.values() for d in a), [])
100 loops, best of 3: 17.1 ms per loop
This can be done in asingle line using list comprehensions :
>>> a = [{'a':3,'b':4}, {'c':14,'d':24}] #List
>>> [v for d in a for v in d.values()] #Comprehension
[3, 4, 14, 24]
In [9]: import operator
In [10]: a = [{'a':3,'b':4}, {'c':14,'d':24}]
In [11]: reduce(operator.add, (d.values() for d in a))
Out[11]: [3, 4, 14, 24]
Bear in mind that Python dictionaries are unordered. This means that the ordering of keys (and their values) within each of the dictionaries is not guaranteed.