belmer01
belmer01

Reputation: 127

Python add item to dictionary value that is a dictionary

I have a dictionary called groups. It looks like this: groups = {'yellow': {}}. How do I add input names to the 'yellow' key?
My code asks for a player's name: name = input("player's name"). If a player's name is John, how do I take that inputted value and store it like this: groups = {'yellow': {'john': []}?

Upvotes: 1

Views: 82

Answers (1)

Kuldeep Singh Sidhu
Kuldeep Singh Sidhu

Reputation: 3856

If you try to set a value to a key that doesn't exist in the dictionary, it will add that to the dictionary

eg: dict[newKey] = someValue will add newKey with someValue to dict

If the key already exists it will update the value

groups = {'yellow': {}}
name = input("player's name")
groups['yellow'][name]=[]
print(groups)
player's nameJohn
{'yellow': {'John': []}}

Upvotes: 6

Related Questions