Luke
Luke

Reputation: 79

Duplicate values in a Python dictionary

I have a dictionary in the following format:

{ 'a' : [1], 'b' : [1,2,3], 'c' : [1,1,2], 'd' : [2,3,4] }

and I want to create a list of the keys which have a '1' in their values.

So my result list should look like:

['a','b','c','c']

I cannot understand how to work with duplicate values. Any ideas how can I get such a list?

Upvotes: 0

Views: 2705

Answers (5)

Enkelli
Enkelli

Reputation: 307

easy way: (Python 3)

d = { 'a' : [1], 'b' : [1,2,3], 'c' : [1,1,2], 'd' : [2,3,4] }  
n = 1
result = []
for key, value in d.items():
    for i in value.count(n):
        res.append(key)

if you want list sorted than:

result.sort()

Upvotes: 2

PanGalactic
PanGalactic

Reputation: 72

The sort must be made on the dictionary to get the expected result. This should work:

list = []
for i in sorted(d.keys()):
   list+=[i for x in d[i] if x == 1]
print list

will output:

 ['a', 'b', 'c', 'c']

Upvotes: 2

Sede
Sede

Reputation: 61225

You can use list comprehensions

>>> d = { 'a' : [1], 'b' : [1,2,3], 'c' : [1,1,2], 'd' : [2,3,4] }
>>> [key for key, values in d.items() for element in values if element==1]
['c', 'c', 'b', 'a']

Here we have two nested for loops in our list comprehension. The first iterate over each key, values pairs in the dictionary and the second loop iterate over each element in the "value" list and return the key each time that element equal to 1. The result list is unordered because dict are unordered which means there are no guarantees about the order of the items.

Upvotes: 5

Brent Washburne
Brent Washburne

Reputation: 13148

This uses two loops, k,v in d.items() which gets each (key,value) pair from the dictionary, and n in v which loops through each value in v:

d = { 'a' : [1], 'b' : [1,2,3], 'c' : [1,1,2], 'd' : [2,3,4] }
l = []
for k,v in d.items():
    for n in v:
        if n == 1:
            l.append(k)
l.sort()

If you want a one-liner:

l = sorted(k for k,v in d.items() for n in v if n == 1)

Upvotes: 2

BrenBarn
BrenBarn

Reputation: 251353

Here is one way:

>>> x = { 'a' : [1], 'b' : [1,2,3], 'c' : [1,1,2], 'd' : [2,3,4] }
>>> list(itertools.chain.from_iterable([k]*v.count(1) for k, v in x.iteritems() if 1 in v))
['a', 'c', 'c', 'b']

If using Python 3, use items instead of iteritems.

Upvotes: 3

Related Questions