简体   繁体   English

用于在Python中通过字典循环语句

[英]For statement looping through dictionary in Python

I need to use a for loop over a dictionary to display all the corresponding values 我需要在字典上使用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))

What I want my for loop to do is to take one item at a time, and then get the corresponding type and location. 我想要for循环执行的操作是一次获取一项,然后获取相应的类型和位置。 Right now, I'm stuck at getting the corresponding types and locations. 现在,我坚持获取相应的类型和位置。

Expected Output would be: 预期输出为:

Starbucks is a Shops & Restaurants located at Track 19.
Supply-Store is a Services located at Central Station.

Assuming each value in your shops dictionary to be another dictionary with type and location. 假设您的shops字典中的每个值都是具有类型和位置的另一个字典。

What you want might be - 您想要的可能是-

for key,value in shops.items():
    print(key + " is a: " + value['type'] + " at : " + value['location']) 

You can use str.format passing the dict using ** to access arguments by name: 您可以使用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))

Output: 输出:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM