[英]For statement looping through dictionary in Python
我需要在字典上使用for循环来显示所有对应的值
shops = {
'Starbucks': {
'type':'Shops & Restaurants',
'location':'Track 19'
},
'Supply-Store': {
'type':'Services',
'location':'Central Station'
}
}
for shop in shops:
print(shop + " is a: " +shop.items(0))
我想要for循环执行的操作是一次获取一项,然后获取相应的类型和位置。 现在,我坚持获取相应的类型和位置。
预期输出为:
Starbucks is a Shops & Restaurants located at Track 19.
Supply-Store is a Services located at Central Station.
假设您的shops
字典中的每个值都是具有类型和位置的另一个字典。
您想要的可能是-
for key,value in shops.items():
print(key + " is a: " + value['type'] + " at : " + value['location'])
您可以使用str.format通过**
传递字典来通过名称访问参数:
Shops = {
'Starbucks': {
'type':'Shops & Restaurants',
'location':'Track 19'
},
'Supply-Store': {
'type':'Services',
'location':'Central Station'
}
}
for shop,v in Shops.items():
print("{} is a {type} located at {location}".format(shop,**v))
输出:
Starbucks is a Shops & Restaurants located at Track 19
Supply-Store is a Services located at Central Station
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.