-2

Is there any way to add multiple value in a dictionary key one by one. Suppose we have dictionary Dict and we want to insert value 3 and 4 with the associated key "xxx", 9 and 10 with key YYY. I want to add them one by one not by making a list.

Example is like this

Dict[xxx]=3
Dict[YYY]=9
Dict[xxx]=4
Dict[YYY]=10

In this way the last value is retaining with the key XXX. Any other way to do this. Please let me know.

NARAYAN CHANGDER
  • 319
  • 4
  • 13
  • Why don't you want a list? That's the most sensible way to do this – doctorlove Jun 20 '16 at 10:26
  • 1
    Just use lists or sets for the value. Use `dict.setdefault()` (so `Dict.setdefault(xxx, []).append(3)` when using a list) if you don't want to have to think about when to create the initial list or set. Or use `collections.defaultdict(list)`, then just append with `Dict[xxx].append(3)`. – Martijn Pieters Jun 20 '16 at 10:27
  • @doctorlove actually the loop is running over key multiple times. For example i have 2 keys X and Y. Both the X and Y are iterated over some finite time (10) and at the end I have to calculate What are the 10 values for X and for Y. – NARAYAN CHANGDER Jun 20 '16 at 10:31
  • @MartijnPieters Thanx – NARAYAN CHANGDER Jun 20 '16 at 10:32

1 Answers1

2

Well, yes and no.

No because it breaks the purpose of the dictionary. A dictionary is supposed to map a key to a unique value.

Yes because we can always store a list associated with the key. So do this:

myDict = {}
myDict[xxx] = []
myDict[xxx].append(3)
myDict[xxx].append(4)
# myDict is now { [3, 4] }
Quirk
  • 1,305
  • 4
  • 15
  • 29