当前位置: 动力学知识库 > 问答 > 编程问答 >

python - 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 )
分享给朋友:
您可能感兴趣的文章:
随机阅读: