{
"1": {
"Furia": "0",
"Chaos": "1"
},
"2": {
"Furia": "0",
"Chaos": "2"
},
"3": {
"Furia": "0",
"Chaos": "3"
},然而,假设在另一场比赛中,两支不同的球队正在使用不同的名字,我如何才能获得这些信息。但是总有两支球队。我只知道如何访问Furia和Chaos。
发布于 2020-06-11 17:10:27
您可以通过使用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发布于 2020-06-11 17:14:12
通过循环它的密钥,我们可以访问它们。
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 3https://stackoverflow.com/questions/62329587
复制相似问题