【问题标题】:Accessing individual values from one key (dictionary)从一个键(字典)访问单个值
【发布时间】:2021-03-20 23:44:58
【问题描述】:
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.

【问题讨论】:

  • 请通过intro tourhelp centerhow to ask a good question 了解本网站的运作方式并帮助您改进当前和未来的问题,从而帮助您获得更好的答案。 “告诉我如何解决这个编码问题?”与 Stack Overflow 无关。您必须诚实地尝试解决方案,然后就您的实施提出具体问题。
  • Stack Overflow 并非旨在取代现有的教程和文档。如果您不知道如何遍历 dict 或访问其元素,则需要重复有关 dicts 的教程。
  • people[key]list 有两个元素,list[0]list[1]
  • 注明。我会更好地在这里提问。

标签: python dictionary f-string


【解决方案1】:

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

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

【讨论】:

  • 非常感谢!我合并了两个字典以获取我的人员列表,但在此之前我不确定如何访问它。
【解决方案2】:

你也可以这样做:

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

【讨论】:

  • 直到这是可能的。我想知道为什么他们删除了函数参数中的元组解包,而不是 for 循环。
猜你喜欢
  • 2016-11-26
  • 2019-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多