python - 具有不同名称的字典以及如何打印名称
问题描述
宠物:制作几个字典,每个字典的名字都是宠物的名字。在每个字典中,包括动物的种类和所有者的名字。将这些字典存储在一个名为 pets 的列表中。接下来,遍历您的列表,并在打印时打印您对每只宠物的了解。
嗨,我有这个问题。我已经完成了解决方案,但我想打印字典名称而不为每个都写 print
解决方案:
jumbo = {"kind":"cat",
"owner":"Rahma",
}
snoopy = {"kind":"dog",
"owner":"fahad",
}
shilla = {"kind":"bird",
"owner":"farooq",
}
pets = [jumbo,snoopy,shilla] # created list
#loop through your list and as you do print everything you know about each pet
for pet in pets :
print ( "jumbo" + " is "+ pet["kind"] + " the owner is " + pet["owner"].title() + "." ) )
问题是我正在尝试使用创建的列表宠物打印每个循环中的名称
解决方案
你可以eval()
像下面这样使用(见参考):
jumbo = {"kind":"cat",
"owner":"Rahma",
}
snoopy = {"kind":"dog",
"owner":"fahad",
}
shilla = {"kind":"bird",
"owner":"farooq",
}
pets = ['jumbo','snoopy','shilla'] # created list
for pet in pets :
print ( (pet) + " is "+ str(eval(pet)["kind"]) + " the owner is " + str(eval(pet)["owner"]) + "." )
输出:
jumbo is cat the owner is Rahma.
snoopy is dog the owner is fahad.
shilla is bird the owner is farooq.
推荐阅读
- python - 如何在 Python 中为 a 替换(环)?
- angular - 角度错误 TS2339:“订阅”类型上不存在属性“查找”
- android - Android 拆分 ABI armeabi-v8a 不工作。我不使用 ndk,但 arm 二进制文件仅适用于 armeabi-v8a
- regex - 仅从文本文件中提取日期并忽略大量数字
- java - Hibernate5 没有与 Spring5 进行交易?
- javascript - 替代 JQuery 切换
- python - 如何显式等待Python Selenium中文本框的属性值发生变化?
- jgrasp - 如何在 JGrasp 上更改小程序的大小?
- regex - 正则表达式组捕获,如何在下一个单词之前停止
- c# - python脚本的异步接口