3

I have a list that I need to make into a dictionary. The list has duplicate (soon to be) keys which have different values. How do I find these keys and append the new values to it?

list=[q:1,w:2,q:7]
dictionary= q:1,7
            w:2

Thanks in advance

user1429839
  • 31
  • 1
  • 2
  • 2
    Lists don't normally have key-value pairs. Does your list consist of tuples or something? Also, in what way specifically do you want to append values to other values -- are you treating them as strings? Because your example suggests they are treated as integers. – Andrew Gorcester Jun 01 '12 at 04:11

1 Answers1

9

Make the values in your dictionary lists, so that you have:

dictionary = {'q': [1, 7],
              'w': [2]
}

etc. ie, your one-item values are one-item lists. This means when you have another 'q', you can do this:

dictionary['q'].append(5)

Except that dictionary['q'] will be a KeyError the first time you do it, so use setdefault instead:

dictionary.setdefault('q', []).append(5)

So now you just need to iterate over every key,value pair in the input list and do the above for each of them.

You might alternatively want to have dictionary be:

dictionary = collections.defaultdict(list)

So you can just do dictionary['q'].append(5) - and it will work the same as the above, in all respects bar one. If, after you have parsed your original list and set all the values properly, your dictionary looks like this:

dictionary = {'q': [1, 7, 5]
              'w': [2, 8, 10, 80]
              'x': [3]
}

And you try to do print(dictionary['y']). What do you expect to happen? If you use a normal dict and setdefault, this is considered an error, and so it will raise KeyError. If you use a defaultdict, it will print an empty list. Whichever of these makes more sense for your code should determine which way you code it.

lvc
  • 34,233
  • 10
  • 73
  • 98
  • 2
    Better yet, use a `collections.defaultdict(list)`- then you can assign or look up just as you would with a normal dictionary. – David Robinson Jun 01 '12 at 04:14
  • @DavidRobinson whether a `defaultdict` is better than setdefault in this case is arguable. Their main benefit comes when the factory function is expensive - but building an empty list isn't. – lvc Jun 01 '12 at 04:18
  • I'd say it's beneficial for the sake of code compactness. You define the dictionary only once, but might get or set values multiple times in the code. – David Robinson Jun 01 '12 at 04:33
  • @DavidRobinson I was about to remind you that getting values isn't affected, since `dictionary['q']` gives a list either way - but then I realised that this isn't just an aesthetic decision. There are potentially use cases either way for what `x = dictionary['keynotset']` should do, and *that* is the difference between `defaultdict` and `dict.setdefault`. I'll update my answer to mention this. – lvc Jun 01 '12 at 04:39