简体   繁体   中英

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.

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 )

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))

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']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM