Mic Rom
Mic Rom

Reputation:

How would you search a dictionary and print out entries with same value

I've been a little confused on how you would go about this, so what would be a good way to do it. For Example: If I had this as my dictionary

dic = [{1:'Dog', 2:'Cat'}, {1:'Bird', 2:'Rat'}, {1:'Turtle', 2:'Cat'}]

The value that you would be looking for is:

value = 'Cat'

And I'm trying to make the program print out each entry that has the Value of 'Cat':

[{1:'Dog', 2:'Cat'}, {1:'Turtle', 2:'Cat'}]

Upvotes: 1

Views: 64

Answers (3)

abarnert
abarnert

Reputation: 365657

If you're just doing this once, just loop over the values:

results = []
for d in dic:
    if value in d.values():
        results.append(d)

This gives you a list of all of the dicts in dic that have a value that matches value.

If you understand comprehensions, you can condense this to:

results = [d for d in dic if value in d.values()]

For example:

>>> value = 'Cat'
>>> results = [d for d in dic if value in d.values()]
>>> results
[{1: 'Dog', 2: 'Cat'}, {1: 'Turtle', 2: 'Cat'}]

If you're doing this a million times, or even 10 times, it will be both simpler and more efficient to build the right data structure. If you want to look up X and get Y simply and quickly, you want a dict with those Xs as keys, and those Ys as values. So:

value_map = {}
for d in dic:
    for v in d.values(): # viewvalues() in 2.7, itervalues in 2.6
        value_map.setdefault(v, []).append(d)

Now, the search is just:

>>> value_map['Cat']
[{1: 'Dog', 2: 'Cat'}, {1: 'Turtle', 2: 'Cat'}]

Can't get any simpler. Or faster.

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 113915

L = [{1:'Dog', 2:'Cat'}, {1:'Bird', 2:'Rat'}, {1:'Turtle', 2:'Cat'}]
maps = {}
for i,d in enumerate(L):
    for v in d.values():
        if v not in maps:
            maps[v] = []
        maps[v].append(i)

for k,vals in maps.items():
    if len(vals)>1:
        print(k)

Output:

Cat

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49318

[dictionary for dictionary in dic if "Cat" in dictionary.values()]

Upvotes: 3

Related Questions