简体   繁体   English

如何获取字典列表中的 object 值?

[英]How to get the object values inside the list of dictionaries?

TEAMS = {
    'teamA': {'name': "Brazil",'points': 0,'goals_for': 0,'goals_difference': 0,'goals_against': 0,},
    'teamB': {'name': "Germany",'points': 0,'goals_for': 0,'goals_difference': 0,'goals_against': 0,},
}

MATCHES = [
    {'home': TEAMS['teamA'], 'goalsHome': 0, 'away': TEAMS['teamB'], 'goalsAway': 0},
]

def showMatch(match):
  print(f"Team {match[home][name]} X {match[away][name]} Team")


showMatch(MATCHES)

I've this list of dictionaries and the dictionary, 'home' is the 'teamA' object that have 'name', 'points'... and I wanna get the home name.我有这个字典列表和字典,'home' 是'teamA' object 有'name','points'......我想得到家的名字。

The output wanted of the print in the showMatch() function is:想要在 showMatch() function 中打印的 output 是:

Team Brazil X Germany Team

[SOLVED] [解决了]

def showMatch():
    for match in MATCHES:
        print(f"{match['home']['name']} {match['goalsHome']} X {match['goalsAway']} {match['away']['name']}\n")

showMatch()

Use a loop.使用循环。

for match in MATCHES:
    showMatch(match)

BTW, in Python that's a list of dictionaries, not an array of objects.顺便说一句,在 Python 中,这是一个字典列表,而不是一个对象数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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