python - pythonic way to filter a dictionary of arrays -


i have dictionary looks this:

  d = { 'a':['a','b','c','d'],        'b':['a','b','c','d'],        'c':['a','b','c','d'],        'd':['a','b','c','d'], }  

i reduce dictionary new 1 contains 2 keys randomly selected full set of keys, , contains values correspond random keys.

here code wrote works, feel there more pythonic way it, 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) k in r) k in r_dict:     = tuple(d[k])     new_a = []     item in a:         if item in r_dict:             new_a.append(item)     new_d[k] = new_a  

"new_d" has filtered dictionary, example:

  {'a': ['a', 'b'], 'b': ['a', 'b']}  

if 'a' , 'b' 2 random keys.

building on fm's, underused set type:

>>> ks = set(random.sample(d, 2)) >>> dict((k, list(ks & set(d[k]))) k in ks) {'a': ['a', 'c'], 'c': ['a', 'c']} 

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -