0
votes

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?

5
Loop through the list in the property. For each time you see 1, append the property name to the result. - Barmar

5 Answers

5
votes

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.

3
votes

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.

2
votes

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)
2
votes

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']
2
votes

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()