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.
Make the value a list, e.g.
  1. 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.
  1. key = "somekey"
  2. a.setdefault(key, [])
  3. a[key].append(1)
Results:
  1. >>> a
  2. {'somekey': [1]}
Next, try:
  1. key = "somekey"
  2. a.setdefault(key, [])
  3. a[key].append(2)
Results:
  1. >>> a
  2. {'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:
  1. a.setdefault("somekey",[]).append("bob")
Results:
  1. >>> a
  2. {'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

Popular posts from this blog

html sitemap 15

html sitemap 16

What are some good programming languages to learn now?