比较python中两个字典列表中的不同键

时间:2017-07-11 19:11:52

标签: python

我正在尝试比较2个字典列表来替换相等的值。例如:

d1 = [{'a': 'hello', 'b':'world','c':'this','d':'is'},{'a':'ddd' ,'b': 'www','c':'hah','d':'tt'},.....]
d2 = [{'Q': 'hello', 'H':'target_word','K':'that','N':'was'},{'Q':'world' ,'H': 'target_word','K':'hah','N':'txt'},.....]

有人可以告诉我如何比较d1中的键(' a'' b')和Q' Q'在d2中,如果它们具有相同的值,那么它必须将d1中的“a”和“b”值替换为d2中的' H< H&#; #39; target_word'

这是我的一次尝试:

for i in d1:
   for j in d2:
    for k in i.keys():
        for k1 in j.keys():
            if j[k1] == i[k]:
                i[k] = j ['H']
                list.append(i[k])

1 个答案:

答案 0 :(得分:2)

这看起来如何?

class Animal:
    def __init__(self, name, height, weight, sound):
        self.name = name
        self.height = height
        self.weight = weight
        self.sound = sound

    def __str__(self):
        return "{} is {} cm tall and {} kilograms and say {}".format(self.name,
                                                                     self.height,
                                                                     self.weight,
                                                                     self.sound)

class Dog(Animal):
    def __init__(self, name, height, weight, sound, owner):
        super(Dog, self).__init__(name, height, weight, sound)
        self.owner = owner


    def __str__(self):
        s = super(Dog, self).__str__()
        return "{} His owner is {}".format(s, self.owner)

spot = Dog("Spot", 53, 27, "Ruff", "Derek")

输出:

d1 = [{'a': 'hello', 'b':'world','c':'this','d':'is'},{'a':'ddd' ,'b': 'www','c':'hah','d':'tt'}]
d2 = [{'Q': 'hello', 'H':'target_word','K':'that','N':'was'},{'Q':'world' ,'H': 'target_word','K':'hah','N':'txt'}]

for input in d1:
    for queries in d2:
        for val in ("a", "b"):
            if input[val] == queries["Q"]:
                input[val] = queries["H"]