【问题标题】:Comparing two Dictionaries and Print the Common比较两个字典并打印共同点
【发布时间】:2015-01-25 01:44:37
【问题描述】:

我有两个带有多个列的制表符分隔文件。我使用了 2 个字典来存储感兴趣的特定列。

import csv
dic1={}
dic2={}
with open("Table1.tsv") as samplefile:
    reader = csv.reader(samplefile, delimiter="\t")
    columns = zip(*reader)
    for column in columns:
        A, B, C, D = columns

with open("Table2.tsv") as samplefile1:
     reader = csv.reader(samplefile1, delimiter="\t")
     columns = zip(*reader)
     for column1 in columns:
        A1, B1, C1 = columns

dic1['PMID'] = A  # the first dictionary storing the data of column "A"
dic2['PMID'] = A1 # the second dictionary storing the data of column "A1"

# statement to compare the data in dic1[PMID] with dic2['PMID'] and print the common

问题:什么是正确的逻辑/或条件语句来比较两个字典并打印两者中的公共数据。

【问题讨论】:

  • 如果我正确理解您的问题,您真正想要比较的是 2 个 列表 A(第一个 csv 的第一列)和 A1(第一列或第二个csv)。这是真的吗?
  • 这正是我的目标
  • 你知道如何比较两列吗? @SergeBallesta

标签: python csv dictionary conditional


【解决方案1】:

您可以将设置交集用作:

>>> d1={'a':2,'b':3,'c':4,'d':5}
>>> d2={'a':2,'f':3,'c':4,'b':5,'q':17}
>>> dict(set(d1.items()) & set(d2.items()))
{'a': 2, 'c': 4}

针对您的具体问题,代码如下:

>>> dic1={}
>>> dic2={}
>>> dic1['PMID']=[1,2,34,2,3,4,5,6,7,3,5,16]
>>> dic2['PMID']=[2,34,1,3,4,15,6,17,31,34,16]
>>> common=list(set(dic1['PMID']) & set(dic2['PMID']))
>>> common
[1, 2, 3, 4, 6, 34, 16]

【讨论】:

  • 您的反馈很有价值......但我不知道如何使用dict 和set 为dic1['PMID'] = A 和dic2['PMID'] = A1 打印两者的共同点。你能告诉我如何在这种情况下应用你的例子吗? @bhat irshad
  • 非常感谢...非常感谢您的意见 :)
猜你喜欢
  • 2019-08-03
  • 2015-01-24
  • 1970-01-01
  • 2020-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-15
相关资源
最近更新 更多