1

I have two array as follows:

a=['history','math','history','sport','math']
b=['literature','math','history','history','math']

I zipped two arrays and used dictionary to see if key and values are equal print me them but the dictionary did not print the cases which are repeated, it print only one one them and i need all of them because I need the number of time they are repeated.

My code:

combined_dict={}
for k , v in zip(a,b):
    combined_dict[k]=v
    print(combined_dict)
TerryA
  • 58,805
  • 11
  • 114
  • 143
Basira
  • 21
  • 1
  • 3

3 Answers3

7

In dictionaries, there are no duplicate keys. So when you have {'history':'literature'} after the first loop, it will get overriden with {'history':'history'}.

Instead of creating a dictionary, why not just loop through the zip(a, b)?

for k, v in zip(a, b):
    if k == v:
        print(k, v)

If you want to have multiple values for one key, then you can use a defaultdict from the collections module:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for k, v in zip(a, b):
...     d[k].append(v)
... 
>>> print(d)
defaultdict(<type 'list'>, {'sport': ['history'], 'math': ['math', 'math'], 'history': ['literature', 'history']})
>>> print(list(d.items()))
[('sport', ['history']), ('math', ['math', 'math']), ('history', ['literature', 'history'])]
>>> for k, v in d.items():
...     if k in v:
...         print k, v
... 
math ['math', 'math']
history ['literature', 'history']
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • thank you.your first suggestion work properly and it was what i meant. so would you please tell me how can i keep all the result items in one list in order to calculate the final number of items in that list? – Basira Oct 02 '13 at 06:58
  • @Basira Put one list inside the other? you can do `a.extend(b)` – TerryA Oct 02 '13 at 07:07
1

A dict cannot have the same key for two entries. For multiple values with same key, you need a dict with a list as value.

Try this:

from collections import defaultdict
a=['history','math','history','sport','math']
b=['literature','math','history','history','math']
combined_dict = defaultdict(list)
for k, v in zip(a,b):
    combined_dict[k].append(v)

print combined_dict
Hari Menon
  • 33,649
  • 14
  • 85
  • 108
0

If you want to get a list of all the items, where there is a match between the two lists, try

>>> print [k for k, v in zip(a, b) if k == v]
    ['math', 'history', 'math']

This gives you a list of matching items, which you can then process further.

Simon Callan
  • 3,020
  • 1
  • 23
  • 34