从一键字典访问单个值

问题描述

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.

解决方法

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

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

你也可以这样做:

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