python - 比较具有不同键的嵌套字典

标签 python python-3.x dictionary

我试图将来自两个不同来源(因此是两个字典)的某些值相互比较,以了解哪些值实际上属于一起。为了说明这一点,我的两个词典的简短版本都带有虚拟数据(为了清晰起见,添加了输入)

dict_1 = 
{'ins1': {'Start': 100, 'End': 110, 'Size': 10}, 
'ins2': {'Start': 150, 'End': 250, 'Size': 100}, 
'del1': {'Start': 210, 'End': 220, 'Size': 10}, 
'del2': {'Start': 260, 'End': 360, 'Size': 100}, 
'dup1': {'Start': 340, 'End': 350, 'Size': 10, 'Duplications': 3}, 
'dup2': {'Start': 370, 'End': 470, 'Size': 100, 'Duplications': 3}}

dict_2 = 
{'0': {'Start': 100, 'Read': 28, 'Prec': 'PRECISE', 'Size': 10, 'End': 110}, 
'1': {'Start': 500, 'Read': 38, 'Prec': 'PRECISE', 'Size': 100, 'End': 600}, 
'2': {'Start': 210, 'Read': 27, 'Prec': 'PRECISE', 'Size': 10, 'End': 220}, 
'3': {'Start': 650, 'Read': 31, 'Prec': 'IMPRECISE', 'Size': 100, 'End': 750}, 
'4': {'Start': 370, 'Read': 31, 'Prec': 'PRECISE', 'Size': 100, 'End': 470}, 
'5': {'Start': 340, 'Read': 31, 'Prec': 'PRECISE', 'Size': 10, 'End': 350}, 
'6': {'Start': 810, 'Read': 36, 'Prec': 'PRECISE', 'Size': 10, 'End': 820}}

我想要比较的是“开始”和“结束”值(以及其他但未在此处指定的值)。如果它们匹配,我想创建一个与此类似的新字典(dict_3):

dict_3 = 
{'ins1': {'Start_d1': 100, 'Start_d2': 100, 'dict_2_ID': '0', etc}
{'del1': {'Start_d1': 210, 'Start_d2': 210, 'dict_2_ID': '2', etc}}

p.s 我需要 Start_d1 和 Start_d2,因为它们的数量可能略有不同 (+-5)。

我在堆栈溢出上尝试了几个选项,例如: Concatenating dictionaries with different keys into Pandas dataframe (我认为这可行,但我在数据帧格式方面遇到了很多麻烦) 和:Comparing two dictionaries in Python (仅当字典没有顶层键时才有效(如此处的 ins1、ins2 等)

有人可以给我一个进一步合作的开始吗?我已经尝试了很多事情,但嵌套字典给我找到的所有解决方案带来了麻烦。

最佳答案

您可以使用 Pandas;这是一个演示:

import pandas as pd

df1 = pd.DataFrame.from_dict(dict_1, orient='index')
df2 = pd.DataFrame.from_dict(dict_2, orient='index')

res = pd.merge(df1, df2, on=['Start', 'End', 'Size'])

print(res)

   Start  End  Size  Duplications  Read     Prec
0    210  220    10           NaN    27  PRECISE
1    340  350    10           3.0    31  PRECISE
2    370  470   100           3.0    31  PRECISE
3    100  110    10           NaN    28  PRECISE

关于python - 比较具有不同键的嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52623755/

相关文章:

使用动态 "is in"约束的 Python 字典架构验证

Python:字典列表,如何获取列表中多个项目的特定键的值?

c# - 字符串数组查找字典

python - 无法在 Jenkins 内部使用 pip

python - 如何使用strptime转换微秒部分的7位时间戳字符串?

如果存在匹配,Python 将 dict 中的值附加到具有两个值的现有 dict 中

python - 如何在保留字典中的顺序的同时重命名键(Python 3.7+)?

python - 负数和正数之间的按位 AND (&)?

java - 在java和python之间传递数据

python - 如何显示第一列的数字并统计出现的次数?