[英]Is there a better way to print these key-value pairs?
所以这是我在Python Crash Course书中第6章的练习6-9中所做的一些代码。
favorite_places = {
'joe': {
'paris': 'france',
'hamburg': 'germany',
'cairo': 'egypt',
},
'anna': {
'tripoli': 'libya',
'tokyo': 'japan',
'moskva': 'russia',
},
'henry': {
'sydney': 'australia',
'quebec': 'canada',
'rio de janeiro': 'brazil',
}
}
for person, places in favorite_places.items():
print(person.title() + "'s favorite places are: ")
places = places.items()
for place in places:
print(place[0].title() + " in " + place[1].title() + ".")
print("\n")
然后输出是这样的:
Joe's favorite places are:
Cairo in Egypt.
Hamburg in Germany.
Paris in France.
有没有一种方法可以只从places变量获取键值并以与我相同的方式打印它,而无需将场所转换为列表? 我觉得这样有点混乱...
通过做这个
places = places.items()
在python 3中,您没有转换为列表,但是您访问的迭代器会产生键,值对,因此这是最好的方法。
(蟒蛇2当量iteritems
,在Python 2 items
返回的夫妻列表,但行为在Python 3已经改变)
(最让我惊讶的是1)您的缩进和2)您最好直接编写而不使用数组或temp变量(将夫妇直接解压缩为2个变量会更优雅,并使用注释中所述的format
更加优雅和高效)
for town,country in places.items():
print("{} in {}.".format(town.title(),country.title())
print("\n")
格式现在对我来说很流行,因此这是另一种很酷的方法:
for name, places in favorite_places.items():
print("{}'s favorite places are:".format(name.capitalize()))
for city, country in places.items():
print("{} in {}.".format(city.capitalize(), country.capitalize()))
print('\n')
稍微短一点的方法(尽管仍然使用列表)是:
for person in favorite_places:
print("%s's favorite places are: " %person.title())
[print('%s in %s.' %(i.title(),z.title())) for i,z in favorite_places[person].items()]
print('\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.