如何访问更改的嵌套字典键?

时间:2020-06-11 16:58:40

标签: python dictionary beautifulsoup nested

{
    "1": {
        "Furia": "0",
        "Chaos": "1"
    },
    "2": {
        "Furia": "0",
        "Chaos": "2"
    },
    "3": {
        "Furia": "0",
        "Chaos": "3"
    },

但是让我们说,在另外一场比赛中,两个不同的球队正在使用不同的名字比赛,我该如何获取这些信息。但是总会有两支队伍。我只知道专门访问Furia和Chaos的方法。

2 个答案:

答案 0 :(得分:0)

您可以使用dict.keys()获取要访问的词典中键的值。 并将值存储在变量中,然后使用这些变量访问所需的值。 例如:

dict1={ "item1":1,"item2":2}
>>> dict1.keys()
dict_keys(['item1', 'item2'])
>>> list_of_keys=[x for x in dict1.keys()]
>>> list_of_keys
['item1', 'item2']
>>> dict1[list_of_keys[1]]
2

答案 1 :(得分:0)

通过循环其键,我们可以访问它们。

nest_dict = {
    "1": {
        "Furia": "0",
        "Chaos": "1"
    },
    "2": {
        "Furia": "0",
        "Chaos": "2"
    },
    "3": {
        "Furia": "0",
        "Chaos": "3"
    }
}

# Outer loop for getting the keys ['1', '2', '3'] 
for key in nest_dict:
   print(f"{key}:")

   # Inner loop for getting the keys ["Furia", "Chaos"]
   for team in nest_dict[key]:
       print(f"{team} scored: {nest_dict[key][team]}")

   # Printing new line for output readablility
   print()

# Alternate Way
print("Alternate Output\n")
for key in nest_dict:
   print(f"{key}:")

   # Since there will always be two teams.
   team1, team2 = nest_dict[key].keys()

   print(team1, team2)
   print(nest_dict[key][team1], nest_dict[key][team2])

   # Printing new line for output readablility
   print()

输出:

1:
Furia scored: 0
Chaos scored: 1

2:
Furia scored: 0
Chaos scored: 2

3:
Furia scored: 0
Chaos scored: 3

Alternate Output

1:
Furia Chaos
0 1

2:
Furia Chaos
0 2

3:
Furia Chaos
0 3