如何比较2个词典?

时间:2016-10-08 22:11:14

标签: python if-statement dictionary

我有两本词典

dict_a = {'x' : 2, 'y' : 3.5, 'z' : 4}
dict_b = {'bob' : ['x', 'y'], 'john' : ['z', 'x'], 'bill' : ['y']}

如果来自dict_b的值匹配,我想比较两个词典并使用dict_a中的键和来自dict_b的值创建一个新词典。我希望看到:

new_dict = {'bob' : [2, 3.5], 'john' : [4, 2], 'bill' : [3.5]}

我尝试过以下代码:

for name, guess in dict_b.items():
    if guess == i in dict_a.values():
        new_dict[name].append(i)  
print(new_dict)

我收到错误NameError: name 'i' is not defined,但我不确定如何定义'i'。

感谢您的帮助

3 个答案:

答案 0 :(得分:3)

非常喜欢:

    import scrapy
    from scrapy import Request, FormRequest
    import json


class ExpertSpider(scrapy.Spider):
    name = "expert"
    allowed_domains = ["expert.fi"]
    start_urls = (
        'http://www.expert.fi/',
    )

def parse(self, response):
    categories = response.xpath('//div[@id="categories-navigation"]//a/@href').extract()
    for cat in categories:
        yield Request(response.urljoin(cat), callback=self.parseCat)

def parseCat(self, response):
    catMenu = response.xpath('//div[@id="category-left-menu"]')
    if catMenu:
        subCats = catMenu.xpath('.//a[@class="category"]/@href').extract()
        for subCat in subCats:
            yield Request(response.urljoin(subCat), callback=self.parseCat)
    else:
        self.parseProdPage(response)
        print "I`ve reached this point"  # debug

def parseProdPage(self, response):
    catId = response.css...
    url = 'https://www.expert.fi/Umbraco/Api/Product/ProductsByCategory'

    data = dict()
    ...
    jsonDict = json.dumps(data)

    heads = dict()
    heads['Content-Type'] = 'application/json;charset=utf-8'
    heads['Content-Length'] = len(jsonDict)
    heads['Accept'] = 'application/json, text/plain, */*'
    heads['Referer'] = response.url

    return Request(url=url, method="POST", body=jsonDict, headers=heads, callback=self.startItemProc)

def startItemProc(self, response):
    resDict = json.loads(response.body)

    item = dict()
    for it in resDict['Products']:
        # Product data
        ...
        item['Category Path'] = it['Breadcrumb'][-1]['Name'] + ''.join([' > ' + crumb['Name']
                                                                for crumb in it['Breadcrumb'][-2::-1]])
        # Make the new request for delivery price
        url = 'https://www.expert.fi/Umbraco/Api/Cart/GetFreightOptionsForProduct'
        data = dict()
        ...
        jsonDict = json.dumps(data)

        heads = dict()
        heads['Content-Type'] = 'application/json;charset=utf-8'
        heads['Content-Length'] = len(jsonDict)
        heads['Accept'] = 'application/json, text/plain, */*'
        heads['Referer'] = item['Product URL']

        req = Request(url=url, method="POST", body=jsonDict, headers=heads, callback=self.finishItemProc)
        req.meta['item'] = item
        yield req

def finishItemProc(self, response):
    item = response.meta['item']
    ansList = json.loads(response.body)
    for delivery in ansList:
        if delivery['Name'] == ...
            item['Delivery price'] = delivery['Price']
    return item

答案 1 :(得分:2)

if guess == i in dict_a.values():

这不符合您的预期。 Python在这里链接运算符,因此您的测试等同于以下内容:

(guess == i) and (i in dict_a.values())

所以这不像在这里执行for循环那样迭代字典值中的变量i

此外,您实际上需要从这些多个键中收集值,因此您希望在此处执行以下操作:

new_dict = {}
for name, guesses in dict_b.items():
    result = []
    for guess in guesses:
        if guess in dict_a:
            result.append(dict_a[guess])
    new_dict[name] = result

然后,您还可以使用列表推导来缩短它:

new_dict = {}
for name, guesses in dict_b.items():
    new_dict[name] = [dict_a[guess] for guess in guesses if guess in dict_a]

最后,你甚至可以将它与词典理解结合起来:

new_dict = { name: [dict_a[guess] for guess in guesses if guess in dict_a] for name, guesses in dict_b.items() }

答案 2 :(得分:1)

这可以通过简单的词典理解来完成:

>>> {k: [dict_a.get(x,x) for x in v] for k, v in dict_b.items()}
{'bob': [2, 3.5], 'john': [4, 2], 'bill': [3.5]}

如果值dict_a存在,则将其替换为dict_b。否则,保留.get(x,x)new_dict = {} for name, guess in dict_b.items(): new_dict[name] = [] for value in guess: if value in dict_a: new_dict[name].append(dict_a[value]) print(new_dict) 中的第二个参数)的那些。

或者,以这种方式修复原始代码:

QList<QTableWidgetItem *>   findItems(const QString & text, Qt::MatchFlags flags) const