在字典列表中将两个相同的值与相同的键组合在一起

时间:2020-09-19 16:25:03

标签: python list dictionary

完全是编程新手..并且需要一些帮助。

我所拥有的是词典列表,格式如下:

a_list = [
    {'ID': 'a', 'Animal': 'dog', 'color': 'white', 'tail': 'yes'},
    {'ID': 'a', 'Animal': 'cat', 'color': 'black', 'tail': 'yes'},
    {'ID': 'b', 'Animal': 'bird', 'color': 'black', 'tail': 'no'},
    {'ID': 'b', 'Animal': 'cat', 'color': 'pink', 'tail': 'yes'}
    {'ID': 'b', 'Animal': 'dog', 'color': 'yellow', 'tail': 'no'}      
   ]

我要的是字典的字典,如下所示:

a_dict = 
    {'a': {'dog': {'color': 'white', 'tail': 'yes'},
           'cat': {'color': 'black', 'tail': 'yes'}},
     'b': {'bird': {'color': 'black', 'tail': 'no'},
           'cat': {'color': 'pink', 'tail': 'no'},
           'dog': {'color': 'yellow', 'tail': 'no'}}}    

5 个答案:

答案 0 :(得分:1)

创建了一个嵌套字典,并删除了以后不需要的所有键。

a_list = [
    {'ID': 'a', 'Animal': 'dog', 'color': 'white', 'tail': 'yes'},
    {'ID': 'a', 'Animal': 'cat', 'color': 'black', 'tail': 'yes'},
    {'ID': 'b', 'Animal': 'bird', 'color': 'black', 'tail': 'no'},
    {'ID': 'b', 'Animal': 'cat', 'color': 'pink', 'tail': 'yes'},
    {'ID': 'b', 'Animal': 'dog', 'color': 'yellow', 'tail': 'no'}      
   ]

a_dict = {}
for a in a_list:
    if a['ID'] in a_dict:
        a_dict[a['ID']][a['Animal']] = a
    else:
        a_dict[a['ID']] = {a['Animal']: a}

for id_ in a_dict:
    for animal in a_dict[id_]:
        del a_dict[id_][animal]['ID']
        del a_dict[id_][animal]['Animal']

输出:

>> a_dict

{'a': {'dog': {'color': 'white', 'tail': 'yes'},
  'cat': {'color': 'black', 'tail': 'yes'}},
 'b': {'bird': {'color': 'black', 'tail': 'no'},
  'cat': {'color': 'pink', 'tail': 'yes'},
  'dog': {'color': 'yellow', 'tail': 'no'}}}

答案 1 :(得分:1)

`"` + s + `"`

打印:

a_list = [
    {'ID': 'a', 'Animal': 'dog', 'color': 'white', 'tail': 'yes'},
    {'ID': 'a', 'Animal': 'cat', 'color': 'black', 'tail': 'yes'},
    {'ID': 'b', 'Animal': 'bird', 'color': 'black', 'tail': 'no'},
    {'ID': 'b', 'Animal': 'cat', 'color': 'pink', 'tail': 'yes'},
    {'ID': 'b', 'Animal': 'dog', 'color': 'yellow', 'tail': 'no'}      
]

a_dict = {}
for v in a_list:
    a_dict.setdefault(v['ID'], {}).setdefault(v['Animal'], {}).update(color=v['color'], tail=v['tail'])

from pprint import pprint
pprint(a_dict)

答案 2 :(得分:0)

使用defaultdict

的简单解决方案
from collections import defaultdict
result = defaultdict(dict)
a_list = [
    {'ID': 'a', 'Animal': 'dog', 'color': 'white', 'tail': 'yes'},
    {'ID': 'a', 'Animal': 'cat', 'color': 'black', 'tail': 'yes'},
    {'ID': 'b', 'Animal': 'bird', 'color': 'black', 'tail': 'no'},
    {'ID': 'b', 'Animal': 'cat', 'color': 'pink', 'tail': 'yes'},
    {'ID': 'b', 'Animal': 'dog', 'color': 'yellow', 'tail': 'no'}      
   ]
for item in a_list:
    result[item['ID']][item['Animal']] = {'color':item['color'], 'tail':item['tail']}

defaultdict(dict,
            {'a': {'dog': {'color': 'white', 'tail': 'yes'},
              'cat': {'color': 'black', 'tail': 'yes'}},
             'b': {'bird': {'color': 'black', 'tail': 'no'},
              'cat': {'color': 'pink', 'tail': 'yes'},
              'dog': {'color': 'yellow', 'tail': 'no'}}})

答案 3 :(得分:0)

与此处提供的其他解决方案非常相似,它使用默认字典。

>>> from collections import defaultdict
>>> d = defaultdict(dict)

>>> for dict_ in a_list:
    ID = dict_.pop('ID')
    animal = dict_.pop('Animal')
    d[ID][animal] = dict_

>>> from pprint import pprint
>>> pprint(dict(d))
{'a': {'cat': {'color': 'black', 'tail': 'yes'},
       'dog': {'color': 'white', 'tail': 'yes'}},
 'b': {'bird': {'color': 'black', 'tail': 'no'},
       'cat': {'color': 'pink', 'tail': 'yes'},
       'dog': {'color': 'yellow', 'tail': 'no'}}}

答案 4 :(得分:0)

您可以在每个步骤中迭代地构造字典,以创建内部字典。 这是针对一般情况的建议实现:

def group_by_nested_keys(elements, keys):
    root = {}
    for element in elements:
        inner_dict = root
        # Create the inner dictionaries as we go through the keys
        # and remove the key from element at the same time 
        for key in keys[:-1]:
            inner_dict = inner_dict.setdefault(element.pop(key), {})

        # When all the dictionaries for the elements are created,
        # assign the element to the most inner dictionary
        inner_dict[element.pop(keys[-1])] = element

    return root



a_dict = group_by_nested_keys(a_list, ["ID", "Animal"])