简体   繁体   English

从一个键(字典)访问单个值

[英]Accessing individual values from one key (dictionary)

people = {"Jenn" : ['renter', 'large room'], 
          "Lana" : ['renter', 'small room'], 
          "Ricky" :['owner', 'large room']
          }

Is there a way to access each individual value for a given key via for loop to print the stats of each person?有没有办法通过 for 循环访问给定键的每个单独值以打印每个人的统计信息? I'm relatively new to Python and I'm having troubles searching for this exact scenario.我对 Python 比较陌生,我在搜索这个确切的场景时遇到了麻烦。 I'm familiar with f-string formatting.我熟悉 f 字符串格式。

Expected output for print() or sys.stderr.write()预期 output 用于print()sys.stderr.write()

Jenn is the renter of a large room.
Lana is the renter of a small room.
Rickey is the owner of a large room.

Use dict.items() to loop through (key, value) tuples:使用dict.items()循环遍历(key, value)元组:

for key, value in people.items():
    print(f"{key} is the {value[0]} of a {value[1]}")

You can also do that:你也可以这样做:

for first, (cat, room) in people.items():
  print(f"{first} is the {cat} of a {room} room")

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

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