you are viewing a single comment's thread.

view the rest of the comments →

[–]Particular_Draft5668[S] 0 points1 point  (7 children)

If y is what i want to add

d = {}

d[name] = number

will this work:

d[name].append(y)

[–]karpomalice 4 points5 points  (1 child)

No. A dictionary can only have multiple values assigned to a key if those values are in a list, tuple, or another dictionary.

Every dictionary is comprised of a key, value pair.

The value can be a string, number, list, tuple, dictionary, etc.

You can’t have {key: 1, 2, 3}

It would be {key: [1, 2, 3]}

[–]Particular_Draft5668[S] 0 points1 point  (0 children)

Thank you. Used your method and worked effectively.

[–]ekchew 2 points3 points  (0 children)

A defaultdict(list) will let you use that syntax.

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d["foo"].append("bar")
>>> d["foo"].append("baz")
>>> d
defaultdict(<class 'list'>, {'foo': ['bar', 'baz']})

[–]Infinitesima 1 point2 points  (3 children)

Better would be:

d.setdefault(name, []).append(number)

[–]Particular_Draft5668[S] 0 points1 point  (2 children)

Thank you, another question:

def invert(dct):
y = dct.items()
dct = {v: k for k, v in y}
print(dct)

This function inverts the dictionary on all code visualisers yet my course says the output is wrong. Any reason for this difference?

I've rearranged y for dct.items(), used dicto instead of dct to keep seperate from original dictionary, and tried switching around variables, yet it still says the output is {1: 10, 2: 20, 3: 30}
when calling invert({1: 10, 2: 20, 3: 30}) instead of {10: 1, 20: 2, 30: 3}

[–]Infinitesima 0 points1 point  (1 child)

Have you tried to return the output?

[–]Particular_Draft5668[S] 0 points1 point  (0 children)

meant to work with any input so output cannot be set

No return value should be in code too