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

时间:2021-03-20 23:44:58

标签: python dictionary f-string

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

有没有办法通过 for 循环访问给定键的每个单独值以打印每个人的统计信息?我对 Python 比较陌生,我在搜索这个确切的场景时遇到了麻烦。我熟悉 f 字符串格式。

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.

2 个答案:

答案 0 :(得分:3)

使用 dict.items() 循环遍历 (key, value) 元组:

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

答案 1 :(得分:1)

你也可以这样做:

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