【问题标题】:For statement looping through dictionary in PythonFor语句在Python中遍历字典
【发布时间】:2015-09-17 10:56:04
【问题描述】:

我需要在字典上使用 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.

【问题讨论】:

    标签: python for-loop dictionary


    【解决方案1】:

    假设您的 shops 字典中的每个值都是另一个具有类型和位置的字典。

    你想要的可能是-

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

    【讨论】:

    • 我不知道是谁否决了这个答案,但它确实有效。标记为已回答,谢谢 Sharon!
    【解决方案2】:

    您可以使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-30
      • 2015-10-30
      • 1970-01-01
      • 2023-03-29
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多