我需要在字典上使用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))
我想让我的循环做的是一次取一个项目,然后得到相应的类型和位置。现在,我坚持要获得相应的类型和位置。
预期产出将是:
Starbucks is a Shops & Restaurants located at Track 19.
Supply-Store is a Services located at Central Station.
答案 0 :(得分:3)
假设shops
字典中的每个值都是另一个具有类型和位置的字典。
你想要的是什么 -
for key,value in shops.items():
print(key + " is a: " + value['type'] + " at : " + value['location'])
答案 1 :(得分:1)
您可以使用str.format使用**
传递dict来按名称访问参数:
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