【问题标题】:Append dictionary in a for loop [duplicate]在for循环中附加字典[重复]
【发布时间】:2019-07-26 13:24:26
【问题描述】:

我想在 for 循环中附加字典,以便得到一个连接字典。此外,所有字典的键不必完全相同。

等价

 one={'a': '2', 'c': 't', 'b': '4'}
 two={'a': '3.4', 'c': '7.6'}
 three={'a': 1.2, 'c': 3.4, 'd': '2.3'}

输出:

combined={'a':['2','3.4','1.2'],'b':'4','c':['t','7.6','3.4'],
                'd':'2.3'}

现在回到原来的问题:

每次 for 循环迭代时,都会生成一个字典,我想附加它。

类似:

 emptydict={}

   for x in z:
      newdict=x.dict()
      emptydict.append(newdict)
      print(emptydict)

【问题讨论】:

  • 伪代码:您必须遍历 newdict 的槽键并查找并附加到 combined[thiskey] ,而不是组合。

标签: python python-3.x dictionary for-loop


【解决方案1】:

试试这个

 one={'a': '2', 'c': 't', 'b': '4'}
 two={'a': '3.4', 'c': '7.6'}
 three={'a': 1.2, 'c': 3.4, 'd': '2.3'}

df = pd.DataFrame([one,two,three])

     a    b    c    d
0    2    4    t  NaN
1  3.4  NaN  7.6  NaN
2  1.2  NaN  3.4  2.3

df.to_dict(orient='list')

输出

{'a': ['2', '3.4', 1.2],
 'b': ['4', nan, nan],
 'c': ['t', '7.6', 3.4],
 'd': [nan, nan, '2.3']}

【讨论】:

    【解决方案2】:

    你可以试试这样的。

    one = {'a': '2', 'c': 't', 'b': '4'}
    two = {'a': '3.4', 'c': '7.6'}
    three = {'a': 1.2, 'c': 3.4, 'd': '2.3'}
    
    new_dict = {}
    list_dict = [one, two, three]
    
    for d in list_dict:
        for key in d:
            if key not in new_dict:
                new_dict[key] = []
            new_dict[key].append(d[key])
    
    print(new_dict)
    

    输出{'a': ['2', '3.4', 1.2], 'c': ['t', '7.6', 3.4], 'b': ['4'], 'd': ['2.3']}

    【讨论】:

      【解决方案3】:

      我已经使用了你的例子来做到这一点 -

      one = {'a': '2', 'c': 't', 'b': '4'}
      two = {'a': '3.4', 'c': '7.6'}
      three = {'a': 1.2, 'c': 3.4, 'd': '2.3'}
      dicts = [one, two, three]
      for dictionary in dicts:
          for key, value in dictionary.items():
              try:
                  new[key].append(value)
              except KeyError:
                  new[key] = [value]
      

      O/P-

      {'a': ['2', '3.4', 1.2], 'c': ['t', '7.6', 3.4], 'b': ['4'], 'd': ['2.3']}
      

      【讨论】:

        【解决方案4】:

        您可以尝试 dict-comprehension 和 list-comprehension :

        new_dict = {k : [j[k] for j in [one,two,three] if k in j] for k in set(list(one.keys())+list(two.keys())+list(three.keys())
        # Output : { 'a': ['2', '3.4', 1.2], 'b': ['4'], 'c': ['t', '7.6', 3.4], 'd': ['2.3']}
        

        如果您希望只有一个元素作为可能值的键不在列表中,请尝试以下操作:

        new_dict =  a = {k : [j[k] for j in [one,two,three] if k in j][0] if len([j[k] for j in [one,two,three] if k in j]) ==1 else [j[k] for j in [one,two,three] if k in j] for k in set(list(one.keys())+list(two.keys())+list(three.keys()))}
        # Output : {'a': ['2', '3.4', 1.2], 'b': '4', 'c': ['t', '7.6', 3.4], 'd': '2.3'}
        

        【讨论】:

          猜你喜欢
          • 2019-06-14
          • 2023-03-20
          • 1970-01-01
          • 2013-08-21
          • 1970-01-01
          • 2017-07-10
          • 1970-01-01
          • 1970-01-01
          • 2016-10-14
          相关资源
          最近更新 更多