0

I would like to know how to extract values in a dictionary that appear for all keys.

So for instance, if i have the following dictionary:

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

I would like to extract the value which exists for all keys, in this instance num_1.

How can i achieve this?

EDIT: how would i store the common value(s) in a list?

juliomalegria
  • 24,229
  • 14
  • 73
  • 89
greenpool
  • 553
  • 4
  • 17
  • 33
  • possible duplicate of [How to find common elements in list of lists?](http://stackoverflow.com/questions/10066642/how-to-find-common-elements-in-list-of-lists) – agf Apr 09 '12 at 02:28

4 Answers4

1

Do something like this:

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

vals = d.values()
uniq = set(vals[0])

for lst in vals[1:]:
    uniq.intersection_update(lst)

# now `uniq` holds the intersected values:
print uniq
> set(['num_1'])

# to get the result as a list:
uniq = list(uniq)
print uniq
> ['num_1']
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

Convert all the values to sets and then take their intersection:

set.intersection(*(set(v) for v in d.values()))
Taymon
  • 24,950
  • 9
  • 62
  • 84
  • 1
    You can't call `set.intersection` with a first argument that isn't a set. You also don't need to make every list into a `set`. – agf Apr 09 '12 at 02:31
  • Sorry, i'm new to 'set'. trying to read up on it now. is there way to store the common value(s) in a list? – greenpool Apr 09 '12 at 02:34
  • You can just convert it using `list`. See the other answers, which are a bit more efficient than this. – Taymon Apr 09 '12 at 02:37
0

My odd working way

vals = [i for v in d.values() for i in v]
set([i for i in vals if vals.count(i) == len(d.values())])
Quang Quach
  • 168
  • 1
  • 2
  • 7
-1

list(set(d['a']) & set(d['c']) & set(d['b']))

This should help

Sachin Tripathi
  • 261
  • 3
  • 3