-6

I've a dictionary as shown below:

dict={0:['hamburger','cheese'], 1:['hamburger']}

I would like to know which is the fastest way to get the every item which are both in 0 and 1, like 'hamburger' in this example

3 Answers3

1

What you want is the intersection of your two dict values. This question gives a solution.

dict={0:['hamburger','cheese'], 1:['hamburger']}
l = list(set(dict[0]) & set(dict[1]))
print(l)
> ['hamburger']
pills
  • 656
  • 1
  • 5
  • 10
0

Try,

[key for key in dict.keys() if 'hamburger' in dict[key]]

The list of indexes will be present in z

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
Deepaklal
  • 119
  • 4
  • hamburger is just for example i want to get every item which are both in 0 and 1 – Giorgi Abashidze Sep 05 '17 at 09:09
  • @GiorgiAbashidze "i want to get every item which are both in 0 and 1". How about you add that sentence to your question because unlike your Original post, this actually tells us what you're asking for. – Zinki Sep 05 '17 at 09:17
0
f=0
for i in d:        #d- dictionary
    if f==0:
        m=set(d[i])
        f=1
        continue
    m=m & set(d[i])   # get intersection. note: there will be no duplicate elements
print list(m)

or

m=set(d[d.keys()[0]])   # ensure dictionary has at least one key

for i in d.keys()[1:]:
    m=m & set(d[i])
print list(m)
akp
  • 619
  • 5
  • 12