2

For each keys in my dict I would like to have unique values : My current implementation :

from collections import defaultdict

a = ["key1", "key2"]
b = ["value1", "value2", "value2", "value3"]

d = defaultdict(list)
for key in a:
    for value in b:
        d[key].append(value)

The current result is :

{'key1': ["value1", "value2", "value2", "value3"] , 'key2': ["value1", "value2", "value2", "value3"]}

but I would like (even in disorder) :

{'key1': ["value1", "value2", "value3"], 'key2': ["value1", "value2", "value3"]}

(where the values for each keys are unique)

8
  • 1
    I find that very hard to believe: b as shown is a set, so won't hold duplicate values. I cannot recreate your claimed output, I get defaultdict(<type 'list'>, {'key2': ['value3', 'value2', 'value1'], 'key1': ['value3', 'value2', 'value1']}) for d, which is already what you say you want.
    – jonrsharpe
    Nov 26, 2014 at 11:31
  • 1
    I've edited your samples into shape, but you have to clarify your question. Your syntax use is entirely incorrect, and confusing. You probably meant a and b to be lists, not sets, for example.
    – Martijn Pieters
    Nov 26, 2014 at 11:32
  • @Hackaholic: please don't add comments about checking your answer. The OP is already notified of your answer, we can all see it just fine. Your comment can be seen as attention spamming, please don't do that.
    – Martijn Pieters
    Nov 26, 2014 at 11:53
  • @Martijn Pieters : sorry, the real context is pretty complicated so I've tried to summarize in a short example which didn't work at all. Thus, I've edited the first post which should now work. Nov 26, 2014 at 13:13
  • I think I get the solution thanks to your answers : d = defaultdict(set) for key in a: for value in b: d[key].add(value) With this, it works just fine Nov 26, 2014 at 13:15

1 Answer 1

3

Try using a set for the dictionary values:

d = defaultdict(set)
for key in a:
    for value in b:
        d[key].add(value)

Note that this will require the values to be hashable.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.