【问题标题】:Comparing key content in Python比较 Python 中的关键内容
【发布时间】:2016-02-18 07:10:55
【问题描述】:

假设我有两个具有相同键的字典

dict1 = {first_letter: a, second_letter:b , third_letter: c}

dict2 = {first_letter: a, second_letter:b , third_letter: d}

我有相同的键,但我想比较键内的内容并打印交叉点

所以如果有另一个字典叫做

intersection = {}

我想要结果

print intersection

{a,b}

我有两个文件中的两个字典,我只想将两个文件的交集放在另一个文件中。因此,如果键包含相同的值,则将其存储到另一个文件中并打印出来。

这是我的代码:

keys = ['lastname', 'firstname', 'email', 'id', 'phone']
dicts = []
second_dicts = []
third_dicts = []
intersection = []

with open("oldFile.txt") as f:
    for line in f:
        # Split each line.
        line = line.strip().split()
        # Create dict for each row.
        d = dict(zip(keys, line))
        # Print the row dict
        print d

        # Store for future use
        dicts.append(d)

print "\n\n"
with open ("newFile.txt") as n:
    for line in n:
        # Split each line.
        line = line.strip().split()
        # Create dict for each row.
        r = dict(zip(keys, line))
        # Print the row dict
        print r
        # Store for future use
        second_dicts.append(r)


print"\n\n"

#shared_items = set(dicts.items()) & set(second_dicts.items())

#print shared_items
#if oldFile has the same content as newFile then make a a newFile 
#called intersectionFile and print 

【问题讨论】:

  • 交集不是字典。
  • 你需要澄清“交叉点”。如果d1 = {'a': 1, 'b': 2}d2 = {'a': 2, 'b': 1},它们的交集是什么?如果是{1, 2},@mirosval 的答案是正确的。如果是空集,@AvinashRaj 是正确的。
  • 但我得到错误打印 set(dicts.values()) & set(second_dicts.values()) AttributeError: 'list' object has no attribute 'values'

标签: python dictionary key


【解决方案1】:

你可以这样做,

>>> dict1 = {'a': 1, 'b':2 , 'c': 3}
>>> dict2 = {'a': 1, 'b':2 , 'c': 4}
>>> {dict1[i] for i in dict1 if dict1[i]==dict2[i]}
set([1, 2])

【讨论】:

    【解决方案2】:

    试试这个:

    set(dict1.values()) & set(dict2.values())
    

    https://docs.python.org/3.5/library/stdtypes.html#set.intersection

    【讨论】:

    • 我不断收到“AttributeError: 'list' object has no attribute 'values'”
    • 来自交集 = set(dicts.values()) & set(second_dicts.values())
    • 您确定您的dictssecond_dicts 是字典而不是列表吗?
    • 哦,你是对的...让我发布我的代码,我认为这会更有用...
    • 您可能应该让 OP 知道您的答案与 @AvinashRaj 之前所做的有所不同,并且他/她的示例对于他/她想要哪个模棱两可。
    【解决方案3】:

    这就是你想要的?

    dict1 = {a: 1, b:2 , c: 3}
    dict2 = {a: 1, b:2 , c: 4}
    
    common = []
    for key, value in dict1.items():
        if dict2[key] == value:
            common.append(value)
    
    intersection = set(common)
    print intersection
    

    【讨论】:

      猜你喜欢
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      • 2011-04-15
      • 2017-09-24
      • 1970-01-01
      相关资源
      最近更新 更多