In the Python dictionary, can 1 key hold more than 1 value?
Well, it depends on how you define a value…
What I mean is, you can put any value type on the value side of a dictionary, you can put a string and then you have one value for this key, or you can put another dictionary and then you might have a multiple values (a value per key on the nested dictionary).
In python, a dictionary can only hold a single value for a given key. However, if you use a relevant data type for that value, you should be able to save multiple values for a single key.
NOTE- Students also search for programming assignment help or Python programming assignment help.
NOTE- Students also search for programming assignment help or Python programming assignment help.
Make the value a list, e.g.
- a["abc"] = [1, 2, "bob"]
UPDATE:
There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.
- key = "somekey"
- a.setdefault(key, [])
- a[key].append(1)
Results:
- >>> a
- {'somekey': [1]}
Next, try:
- key = "somekey"
- a.setdefault(key, [])
- a[key].append(2)
Results:
- >>> a
- {'somekey': [1, 2]}
The magic of
setdefault is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault returns the key you can combine these into a single line:
- a.setdefault("somekey",[]).append("bob")
Results:
- >>> a
- {'somekey': [1, 2, 'bob']}
You should look at the
dict methods, in particular the get() method, and do some experiments to get comfortable with this.
Comments
Post a Comment