You can do this:
s = dict([ (k,r) for k,r in mydict.iteritems() if r['x'] > 92 and r['x'] < 95 and r['y'] > 70 and r['y'] < 75 ])
This takes a dict as you specified and returns a 'filtered' dict.
Answer from adamk on Stack OverflowYou can do this:
s = dict([ (k,r) for k,r in mydict.iteritems() if r['x'] > 92 and r['x'] < 95 and r['y'] > 70 and r['y'] < 75 ])
This takes a dict as you specified and returns a 'filtered' dict.
If dct is
{'test1420': {'y': '060', 'x': '070', 'fname': 'test1420'},
'test277': {'y': 72, 'x': 94, 'fname': 'test277'},}
Perhaps you are looking for something like:
[ subdct for key,subdct in dct.iteritems()
if 92<subdct['x']<95 and 70<subdct['y']<75 ]
A little nicety is that Python allows you to chain inequalities:
92<dct[key]['x']<95
instead of
if r['x'] > 92 and r['x'] < 95
Note also that above I've written a list comprehension, so you get back a list (in this case, of dicts).
In Python3 there are such things as dict comprehensions as well:
{ n: n*n for n in range(5) } # dict comprehension
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
In Python2 the equivalent would be
dict( (n,n*n) for n in range(5) )
I'm not sure if you are looking for a list of dicts or a dict of dicts, but if you understand the examples above, it is easy to modify my answer to get what you want.
Original data:
list_of_dictionaries = [{'key1':'value1'},{'key2':'value2'},{'key3':['item1','item2','item3']}]Desired output
{'key1':'value1','key2':'value2','key3': ['item1','item2','item3']}Standart loop does the job, but i don't like it
empty_dictionary = {}
for item in list_of_dictionaries:
for k, v in item.items():
empty_dictionary[k] = vHow can i do it using list comprehension?
I'm trying to create the following dictionary:
{ 0:3,0:4,0:5 }
And I did:
{ 0:i for i in range(3,6) }
Which doesn't work. Any idea how to? Maybe I can make it through a list of pairs? But is this way possible?
Use a dict comprehension (Python 2.7 and later):
{key: value for key, value in zip(keys, values)}
Alternatively, use the dict constructor:
pairs = [('a', 1), ('b', 2)]
dict(pairs) # β {'a': 1, 'b': 2}
dict((k, v + 10) for k, v in pairs) # β {'a': 11, 'b': 12}
Given separate lists of keys and values, use the dict constructor with zip:
keys = ['a', 'b']
values = [1, 2]
dict(zip(keys, values)) # β {'a': 1, 'b': 2}
In Python 3 and Python 2.7+, dictionary comprehensions look like the below:
d = {k:v for k, v in iterable}
For Python 2.6 or earlier, see fortran's answer.
Using defaultdict:
from collections import defaultdict
D = defaultdict(list)
[D[v].append(i) for i, v in enumerate(A)]
Using setdefault:
D = {}
[D.setdefault(v, []).append(i) for i, v in enumerate(A)]
I can't figure any mean to use a dictionnary comprehension without sorting the data:
from itertools import groupby
from operator import itemgetter
{v: ids for v, ids in groupby(enumerate(sorted(A)), itemgetter(1))}
Performances:
from collections import defaultdict
from itertools import groupby
from operator import itemgetter
from random import randint
A = tuple(randint(0, 100) for _ in range(1000))
def one():
D = defaultdict(list)
[D[v].append(i) for i, v in enumerate(A)]
def two():
D = {}
[D.setdefault(v, []).append(i) for i, v in enumerate(A)]
def three():
{v: ids for v, ids in groupby(enumerate(sorted(A)), itemgetter(1))}
from timeit import timeit
for func in (one, two, three):
print(func.__name__ + ':', timeit(func, number=1000))
Results (as always, the simplest win):
one: 0.25547646999984863
two: 0.3754340969971963
three: 0.5032370890003222
You can do the following
d = collections.defaultdict(list)
for i,v in enumerate(A):
d[v].append(i)
You can see that the values of the resulting dictionary are lists, the elements of which are to be produced while traversing. If you insist on doing a dict comp, you have to first find all the (value, [indices]), then do a dict comp on [(k,[v])], which just means extra acrobatics without any benefit.