简体   繁体   中英

How do I create a dictionary within another dictionary?

Right now I'm making a python program that takes names and stats and records them. To do this I am attempting to create a nested dictionary that looks something like this example.

playerData = {"Jack": {"strength": 10, "intelligence": 5}, "John": {"strength": 8, "intelligence": 10}}

My problem arises when I try to make it. I have my program structured to first create a list of names, and then a list of stat categories, and I'm trying to create a dictionary within a dictionary to create it. I have a function called collectPlayerAttributes that creates a list of stat categories, an example being

 ["strength", "intelect", "charisma"]

. What I'm trying to do is pull the values from that list and enter them as keys into the dictionary playerData. Using the example list from earlier this would look something like

 {"Jack": {"strength": 10, "intelect": 5, "charisma": 8}}

The values attached to the keys are just placeholders, but in the end I'm planning to do something along the lines of

 input("What is Jack's strength? ")

and put the result there. My code so far is

playerData = {}
y = 0
for i in players:
  playerData[str(players[y])] = {#What goes here?}
  y += 1

If you just want to create a dict where all players have an entry, you can create an empty dict for each of them:

playerData = {i:{} for i in players}

If you then ask the user for a strength value you can do this:

def updatePlayerAttribute(playerData, name, attribute):
    value = input(f'What is the {attribute} of {name}?')
    playerData[name][attribute] = value

name = "Jack"
attribute = "strength"
updatePlayerAttribute(playerData, name, attribute)
print(playerData)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM