2017-02-24 92 views
0

我有這本字典。檢索嵌套字典中的唯一鍵列表

d = {'match1': {'player1': 57, 'player2': 38}, 
    'match2': {'player1': 42, 'player3': 9}, 
    'match3': {'player2': 41, 'player3': 91, 'player4': 63}} 

我想一個循環,與指數運行player1, player2, player3, player4. 如何編寫循環結構?可能還有更多玩家

我想:

for i in ["player1", "player2", "player3", "player4"]: 

但這隻能用於正好4名球員。如果玩家多多少少該怎麼辦?

回答

0

這聽起來像你想構造通過將數字後綴附加到一個常量字符串的關鍵。使用str.format

for i in range(1,5): 
    key = 'player{}'.format(i) 
    print(key) # player1, player2, ... 
0

迭代所有匹配,收集所有遇到的玩家名稱進行設置。之後迭代該集。

players = {player for match_name in d for player in d[match_name]]} 
for player in players: 
    print(player)