根据python中的索引合并包含两个列表的字典 [英] Merge two list contained dictionary based on its index in python

查看:528
本文介绍了根据python中的索引合并包含两个列表的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个包含多个字典的列表,每个字典都有一个作为值的列表,这些是我的列表:

I have two list contain multi dictionary, each dictionary has a list as value, these are my list:

list1 = [{'a':[12,22,61],'b':[21,12,50]},{'c':[10,11,47],'d':[13,20,45],'e':[11,24,42]},{'a':[12,22,61],'b':[21,12,50]}]
list2 = [{'f':[21,23,51],'g':[11,12,44]},{'h':[22,26,68],'i':[12,9,65],'j':[10,12,50]},{'f':[21,23,51],'g':[11,12,44]}]

就我而言,我需要将这些列表与此规则合并:

In my case, i need to merge these list with this rule:

  1. 仅第一个列表(列表1)中的词典可以通过以下方式合并 第二个列表(list2)中具有相同列表索引的字典
  2. 将这两个列表合并后,必须根据其值的第三个数字对每个字典进行排序
  1. Dictionary from the first list (list1) only can be merged by dictionary from the second list (list2) with the same listing index
  2. After both of these list are merged, each dictionary has to be sorted based on the third number of its value

这是基于上述两个规则的预期结果:

This is the expected result based on two rule above:

result = [
    {'a':[12,22,61],'f':[21,23,51],'b':[21,12,50],'g':[11,12,44]},
    {'h':[22,26,68],'i':[12,9,65],'j':[10,12,50],'c':[10,11,47],'d':[13,20,45],'e':[11,24,42]},
    {'a':[12,22,61],'f':[21,23,51],'b':[21,12,50],'g':[11,12,44]}
    ]

我该怎么做?可以在python中使用内联循环吗?

How can i do that? is it possible to be done in python with inline looping?

推荐答案

一行(如果您不考虑导入):

In one line (if you do not count with the import):

from collections import OrderedDict

[OrderedDict(sorted(dict(d1.items() + d2.items()).items(), key=lambda x: x[1][-1],
                    reverse=True)) for d1, d2 in zip(list1, list2)]

[OrderedDict([('a', [12, 22, 61]),
              ('f', [21, 23, 51]),
              ('b', [21, 12, 50]),
              ('g', [11, 12, 44])]),
 OrderedDict([('h', [22, 26, 68]),
              ('i', [12, 9, 65]),
              ('j', [10, 12, 50]),
              ('c', [10, 11, 47]),
              ('d', [13, 20, 45]),
              ('e', [11, 24, 42])]),
 OrderedDict([('a', [12, 22, 61]),
              ('f', [21, 23, 51]),
              ('b', [21, 12, 50]),
              ('g', [11, 12, 44])])]

这在Python 2.7中有效.

This works in Python 2.7.

这篇关于根据python中的索引合并包含两个列表的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆