使用通用键/值在python中合并字典 [英] merge dictionaries in python with common key/value

查看:73
本文介绍了使用通用键/值在python中合并字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找将Python中的字典与具有共同值然后为键的字典合并的方法.当前,我在循环内部的循环中有一个讨厌的循环.必须有更好的方法...

I am looking to merge dictionaries in Python with dictionaries that have a common value then key. Currently, I have a nasty loop inside of a loop inside of a loop. There has to be a better way...

我所拥有的是一本字典,该字典具有一个数字键和该值的数字列表,然后是第二本字典,其具有与值列表中的数字之一相对应的键和与该数字相关联的浮点数.它们的格式如下(尽管更大):

What I have is one dictionary with a single digit key and a list of numbers for that value, then a second dictionary with a key that corresponds with one of the numbers in the value list and a float associated with that number. They are formatted like this (although much larger):

dict1 = {0:[3, 5, 2, 7], 1:[1, 4, 0, 6]}
dict2 = {0:0.34123, 1:0.45623, 2:0.76839, 3:0.32221, 4:0.871265, 5:0.99435, 6:0.28665, 7:0.01546}

我想将它们合并,使它们看起来像这样:

And I would like to merge them so they look like this:

dict3 = {0:[0.32221, 0.99435, 0.76839, 0.01546], 1:[0.45623, 0.871265, 0.034123, 0.28665]}

是否有比嵌套多个for循环更简单的方法?任何帮助将不胜感激!

Is there a simpler way to do this than several nested for loops? Any help would be massively appreciated!

推荐答案

您可以使用dict理解中的嵌套列表理解来做到这一点:

You can do this using a nested list comprehension inside a dict comprehension:

dict3 = {k: [dict2[i] for i in v] for k, v in dict1.items()}

这基本上将迭代第一个字典中的所有k/v-组合. k保留为结果字典的键,而vdict2中所有应使用值的所有索引的列表.因此,我们遍历v中的元素,并从我们要获取的dict2中收集所有项目,将它们组合在列表中(使用列表推导),并将该结果用作结果字典的值.

This will basically iterate through all k/v-combinations within the first dictionary. The k is kept as the key for the resulting dictionary, and the v is a list of all indices in dict2 which values should be used. So we iterate through the elements in v and collect all items from dict2 we want to take, combine those in a list (using the list comprehension) and use that result as the value of the result dictionary.

这篇关于使用通用键/值在python中合并字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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