pythonic way to filter a dictionary of arrays
I have a dictionary that looks something like this:
d = { 'a':['a','b','c','d'],
'b':['a','b','c','d'],
'c':['a','b','c','d'],
'd':['a','b','c','d'], }
I would like to reduce this dictionary into a new one that contains 2 keys randomly selected from the full set of keys, and also only contains values that correspond to those random keys.
Here is the code I wrote that works, but I feel like there is probably a more pythonic way to do it, any suggestions?
import random
d = { 'a':['a','b','c','d'],
'b':['a','b','c','d'],
'c':['a','b','c','d'],
'd':['a','b','c','d'], }
new_d = {}
r = d.keys()
random.shuffle(r)开发者_开发百科
r = r[:2]
r_dict = dict( (k,True) for k in r)
for k in r_dict:
a = tuple(d[k])
new_a = []
for item in a:
if item in r_dict:
new_a.append(item)
new_d[k] = new_a
"new_d" has filtered dictionary, for example:
{'a': ['a', 'b'], 'b': ['a', 'b']}
If 'a' and 'b' are the two random keys.
Building on FM's, with the underused set type:
>>> ks = set(random.sample(d, 2))
>>> dict((k, list(ks & set(d[k]))) for k in ks)
{'a': ['a', 'c'], 'c': ['a', 'c']}
How about the following:
import random
rk = random.sample(d.keys(),2)
new_d = {}
for k in rk:
new_d[k] = list(set(d[k]).intersection(rk))
ks = set(random.sample(d.keys(), 2))
nd = dict( (k, list(v for v in d[k] if v in ks)) for k in ks )
加载中,请稍侯......
精彩评论