【问题标题】:Python: How to loop through a dictionary mutiple times?Python:如何多次循环遍历字典?
【发布时间】:2020-11-10 21:02:37
【问题描述】:

我想创建一个代码,其中包含可以打印出不同类型结果的字典。我有两本词典。其中一个具有不同的结果集,而其他字典值是空字符串,我希望将这些值存储在其中并以不同的结果集多次打印。还想知道是否有可能创建另一个循环,其中只在字典的每个键中打印第一个字母。到目前为止,这是我的代码。

a_dict = {'A': [['LA', 'Sallys', 'Associate '], ['Hollywood', 'Tonys', 'Shelf'],['Compton', 'Sally', 'Shelves']],'B': [['SAC', 'Sallys', 'Associate '], ['Townsland', 'Tonys', 'Shelf'], ['Compton', 'Tiffanys', 'Shelves']]}

b_dict = {'Site':"", 'Store':"", 'Station':""}

        for key in a_dict:

       

        b_dict.update(a_dict) 

        print(b_dict[key])

        #print(b_dict[key[0]])

我希望输出是这样的

'Site':"LA", 'Store':"Sallys", 'Station':"Associate"

“站点”:“好莱坞”,“商店”:“托尼斯”,“车站”:“货架”

“站点”:“康普顿”,“商店”:“莎莉”,“车站”:“货架”

还有这样的

“站点”:“L”,“商店”:“S”,“车站”:“A”

“站点”:“H”,“商店”:“T”,“车站”:“S”

“站点”:“C”,“商店”:“S”,“车站”:“S”

【问题讨论】:

    标签: python loops dictionary key key-value


    【解决方案1】:
    output = [
    {'Site':val[0], 'Store':val[1], 'Station':val{3]}
    for vals in a_dict.values()
    for val in vals
    ]
    

    这将为您提供所需的 b_dicts 列表

    【讨论】:

      【解决方案2】:

      所以你有这个 a_dict 和键 AB 这似乎是你所说的“结果”,值是一个“站点”列表,其中包含站点名称、商店和站点的数据.对吧?

      a_dict = {
        'A': [
                 ['LA', 'Sallys', 'Associate'], 
                 ['Hollywood', 'Tonys', 'Shelf'],
                 ['Compton', 'Sally', 'Shelves']
             ],
        'B': [
                 ['SAC', 'Sallys', 'Associate '], 
                 ['Townsland', 'Tonys', 'Shelf'], 
                 ['Compton', 'Tiffanys', 'Shelves']
             ]
       }
      

      b_dict 的键是:

      b_keys = ["Site", "Store", "Station"]
      

      您可以使用zip 即时创建b_dict,如果您只需要打印它:

      for key, sites in a_dict.items():
          # print(key)
          for b_values in sites:
              print(dict(zip(b_keys, b_values)))
      

      但是如果你以后需要做其他事情,你可以很容易地给它起个名字b_dict = dict(zip(b_keys, b_values))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 2022-09-22
        • 1970-01-01
        • 2013-11-29
        • 2023-01-20
        相关资源
        最近更新 更多