【问题标题】:Use .join() to manipulate inner dictionary elements of a nested dictionary使用 .join() 操作嵌套字典的内部字典元素
【发布时间】:2016-05-17 00:56:34
【问题描述】:

我有一个问题。我试图将其他问题的信息放在一起,但没有成功。 假设我有以下格式的数据:

file_list = ["f1", "f2", "f3"]
inner_dict = {1: "one", 2: "two", 3: "three"}
outer_dict = {}

for f in file_list:
     outer_dict[f] = inner_dict

我的目标是通过以下方式打印(保存到文件中):

f1, 1, one
f1, 2, two
f1, 3, three
f2, 1, one
f2, 2, two
f2, 3, three
f3, 1, one
f3, 2, two
f3, 3, three

为了这个目标,我开始关注outer_dict的项目,并设法将它们分开打印,但我不知道如何进一步加入(更重要的是,如果这是最直接的方法)。

for key, value in outer_dict.items():
    inn_keys = value.keys()
    inn_values = value.values()
    b1 = "\n".join([str(x) for x in inn_keys] )
    b2 = "\n".join([str(x) for x in inn_values] )

感谢您的任何建议。

【问题讨论】:

    标签: python python-2.7 dictionary join python-2.x


    【解决方案1】:

    这个oneliner怎么样 - 只需连接元组(即[(i,)+j for j in inner_dict.items() for i in file_list])并将元组列表扁平化为一个简单的列表。

    [item for sublist in [(i,)+j for j in inner_dict.items() for i in file_list] for item in sublist]
    

    输出-

    ['f1', 1, 'one', 'f2', 1, 'one', 'f3', 1, 'one', 'f1', 2, 'two', 'f2', 2, 'two', 'f3', 2, 'two', 'f1', 3, 'three', 'f2', 3, 'three', 'f3', 3, 'three']
    

    注意如果使用字典维护顺序,最好使用OrderedDict

    【讨论】:

      【解决方案2】:

      既然您想将其保存为 csv 文件,请查看这是否有帮助。如果订单很重要,您可以使用OrderedDict

      from collections import OrderedDict
      import csv
      
      
      file_list = ["f1", "f2", "f3"]
      inner_dict = {1: "one", 2: "two", 3: "three"}
      outer_dict = OrderedDict()
      
      for f in file_list:
          outer_dict[f] = inner_dict
      
      rows = []
      for i,k in outer_dict.items():
          for m,n in k.items():
              rows += [[str(x) for x in [i, m, n]]]
      
      with open('test.csv', 'w') as f:
          _csv = csv.writer(f, escapechar=' ', quoting=csv.QUOTE_NONE)
          [_csv.writerow(row) for row in rows]
      

      test.csv 文件如下所示:

      f1,1,one
      f1,2,two
      f1,3,three
      f2,1,one
      f2,2,two
      f2,3,three
      f3,1,one
      f3,2,two
      f3,3,three
      

      【讨论】:

        【解决方案3】:

        似乎其他答案假定字典中的确定顺序。但是字典do not have a deterministic order。其实在 Python 2 中可以设置hash_randomization。只要从命令行选项-R开始:

        python -R
        

        这是default in Python 3

        因此,为了使这项工作更可靠,并且也适用于 Python 3,请对内部字典的键进行排序。由于它被多次使用,因此只对其排序一次并在文件列表的所有迭代中重复使用它:

        from __future__ import print_function
        
        file_list = ["f1", "f2", "f3"]
        inner_dict = {1: "one", 2: "two", 3: "three"}
        
        inner_list = [', '.join([str(key), inner_dict[key]]) for key in sorted(inner_dict)]
        
        for fname in file_list:
            for inner in inner_list:
                print('{}, {}'.format(fname, inner))
        

        输出:

        f1, 1, one
        f1, 2, two
        f1, 3, three
        f2, 1, one
        f2, 2, two
        f2, 3, three
        f3, 1, one
        f3, 2, two
        f3, 3, three
        

        【讨论】:

          【解决方案4】:

          修补您的代码以使其正常工作将如下所示:

          b1 = ""
          for key, value in outer_dict.items():
              b1 += "\n".join([','.join([key,str(k),v]) for k, v in value.items()]) + '\n'
          

          但是,我认为你做的比在 python 中更复杂,一个更简单的解决方案是使用嵌套循环:

          s = ""
          for f in file_list:
              for k,v in inner_dict.items():
                  s+= ','.join([f,str(k),v]) + "\n"
          

          我相信你可以找到一个可以为你做这件事的单线。

          【讨论】:

            【解决方案5】:

            你的情况可以使用双join,记得把你的ints转换成str

            print '\n'.join([', '.join([e1] + [str(e) for e in e2]) for e1, e2 in zip(file_list, inner_dict.items())])
            
            f1, 1, one
            f2, 2, two
            f3, 3, three
            

            【讨论】:

              【解决方案6】:

              你可以这样做:

              string_list = []
              
              for el1 in file_list:
                  for el2 in inner_dict.items():
                      string_list.append(", ".join([el1, str(el2[0]), el2[1]]))
              
              print(string_list)
              

              输出:

              ['f1, 1, one', 
               'f1, 2, two', 
               'f1, 3, three', 
               'f2, 1, one', 
               'f2, 2, two', 
               'f2, 3, three', 
               'f3, 1, one', 
               'f3, 2, two',
               'f3, 3, three']
              

              【讨论】:

              • 嗨,谢谢你的回答,我需要打印我在问题中发布的内容(所以每行 3 个值用逗号分隔),因为我想将每一行保存在 csv 文件中.
              • 另外,我想借此机会了解一下 .join() 在这个特定示例中的工作原理。
              • "separator".join(iterable) 使用separator 字符串连接传入的iterable 的字符串。
              • 最终输出不是我需要的,请查看最初的问题,谢谢,S.(基本上我需要为所有相应项目“重复”外键)。
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2021-09-18
              • 2021-04-28
              • 2018-11-22
              • 2021-12-20
              • 1970-01-01
              • 1970-01-01
              • 2021-02-01
              相关资源
              最近更新 更多