Python-比较两个字典[区分大小写的值]

时间:2018-07-14 12:20:12

标签: python dictionary

我正在尝试比较Python中的两个字典(包含数组的列表)。

这是两个字典:

tag=[{'Key': 'Base', 'Value': 'ny'}, {'Key': 'Name', 'Value': 'newyork'}]

filters=[{'Key': 'Name','Value': ['Newyork', 'newyork','NewYork']}]

这里的任务是将filters字典与tag字典进行比较。

以下我尝试过的方法都无效:

>>> tag == filters
False
>>> tag[1] == filters
False
>>> tag[1] == filters[0]
False

我想检查tag是否具有与filters匹配的数组,它应该返回true

也许它可以比较数组中的Key的值,因为它具有完全匹配的字符串,但是对于Value,它在不同情况下写的是相同的字符串,则不匹配。

在比较时我想介绍的内容:

  • 将其与字典中的每个数组进行比较(如果有任何匹配的数组应返回true)
  • 考虑keyvalues的所有可能情况:'Name','name','NAME''Newyork', 'newyork','NewYork'

任何帮助表示赞赏。 预先感谢!

2 个答案:

答案 0 :(得分:1)

一开始它们是很奇怪的数据结构,但是我将其识别为aws cli / api返回的东西。我敢打赌,有一种cli / api方式可以过滤您要尝试执行的操作,您实际上应该发布一个有关您要从aws查询的内容的问题(see)。但目前暂时忽略:

请注意,let toHome = StackActions.reset({ index: 0, actions: [NavigationActions.navigate({routeName: 'Home', params: {foo: 'bar'}})] }); this.props.navigation.dispatch(toHome) 不是字典,而是字典列表。您需要首先选择其中包含tag的字典。

Key:Name

或者,您想选择与过滤器具有相同next(element for element in tag if element['Key'] == 'Name') => {'Key': 'Name', 'Value': 'newyork'} 的字典。

Key:xxx

现在您想将所选词典中的next(element for element in tag if element['Key'] == filters[0]['Key']) => {'Key': 'Name', 'Value': 'newyork'} 与过滤器Value

进行比较
Value

一行

selectedDict=next(element for element in tag if element['Key'] == filters[0]['Key'])
selectedDict['Value'] in filters[0]['Value']
=> True

答案 1 :(得分:0)

这会将您的Dictionary转换成小写,丢弃多余的大小写(例如NewYork,NEWYORK,ETC。然后比较返回的Dictionary的匹配项。

import re

tag=[{'Key': 'Base', 'Value': 'ny'}, {'Key': 'Name', 'Value': 'newyork'}]
filters=[{'Key': 'Name','Value': ['Newyork', 'newyork','NewYork']}]

def dict_to_lower(dct):
    tmp = []
    for item in dct:
        #check for one value, change to lower case
        if re.search(r'[\,]', str(item['Value'])) is None:
            item['Key'] = str(item['Key']).lower()
            item['Value'] = str(item['Value']).lower()
            tmp.append(item)
        #else multiple values in list, change to lower, discard all but one
        else:
            item['Key'] = str(item['Key']).lower()
            item['Value'] = re.search(r'(\w+)', str(item['Value']).lower()).group(0)
            tmp.append(item)

    dct = tmp


    return dct

def compare_lists(tag, filters):
    #compare tag to filters return matches
    check = set([(d['Key'], d['Value']) for d in filters])
    return [d for d in tag if (d['Key'], d['Value']) in check]

tag = dict_to_lower(tag)
filters = dict_to_lower(filters)

if compare_lists(tag, filters):
    #Rest of your code here