1

I have two OrderedDict dictionaries, and I want to retrieve values for matching keys in both dictionaries:

>>> from collections import OrderedDict
>>> d1 = OrderedDict()
>>> d2 = OrderedDict()

>>> d1["A"] = 2
>>> d1["B"] = 3
>>> d1["C"] = 2

>>> d2["D"] = 90
>>> d2["B"] = 11
>>> d2["C"] = 25

>>> # search both dicts and output values where key matches

(3, 11)
(2, 25)
vaultah
  • 44,105
  • 12
  • 114
  • 143
Juli
  • 159
  • 1
  • 2
  • 8
  • Good. Write so me code to do that and you're done. – juanchopanza Apr 25 '14 at 09:18
  • 5
    The world is unfair. [Certain duplicates](http://stackoverflow.com/questions/23286254/convert-list-to-a-list-of-tuples-python), no effort questions are upvoted like crazy, and certain ones are downvoted! – devnull Apr 25 '14 at 09:22
  • @devnull Up-voted too, which is a sign of the times :) – juanchopanza Apr 25 '14 at 09:41
  • @juanchopanza I didn't suggest that the question be upvoted. (I didn't vote on it either way.) But I do expect the community to be a _bit_ consistent. – devnull Apr 25 '14 at 09:44
  • @devnull I didn't mean to imply that. In my view it is fully deserving of a down-vote, and so is the one you linked. – juanchopanza Apr 25 '14 at 09:49

3 Answers3

5
print [(d1[key], d2[key]) for key in d1.viewkeys() & d2]
# [(2, 25), (3, 11)]

d1.viewkeys() & d2 is used to get the keys which are present in both the dictionaries. Once we get that, simply get the values corresponding to that from both the dictionaries.

This works because, as per the Dictionary View Objects Python 2.7 Documentation,

Keys views are set-like since their entries are unique and hashable.

Since viewkeys are already set-like, we can use set operations on them directly.

Note: If you are using Python 3.x, then you have to use keys function, like this

print([(d1[key], d2[key]) for key in d1.keys() & d2])

because, as per the Dictionary View Objects Python 3.x Documentation,

The objects returned by dict.keys(), dict.values() and dict.items() are view objects.

Since keys itself returns a view object, and as their entries are unique and hashable, we can use that like set.

Note: In Python 2.x, dict.keys returns a list of keys. Since we cannot do set operations on a list, we cannot use the Python 3.x solution.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
3

You can easily do that as:

res = [(d1[i], d2[i]) for i in d1 if i in d2]

>>> print res
[(3, 11), (2, 25)]
sshashank124
  • 31,495
  • 9
  • 67
  • 76
1
a = d1.keys()
b = d2.keys()
for i in range(0, len(a)):
  for j in range(0, len(b)):
    if (a[i]==b[j]):
      print d1[a[i]], d2[b[j]] 
vaultah
  • 44,105
  • 12
  • 114
  • 143
Nandha Kumar
  • 413
  • 8
  • 18