简体   繁体   English

Python词典列表:如何判断值是否不存在

[英]Python list of dictionaries: How to tell if value doesn't exist

I have a JSON query that returns a list of dictionaries that I want to modify. 我有一个JSON查询,返回我想要修改的字典列表。 Here is the part that interests me in the response: 以下是我对回复感兴趣的部分:

{
    #...
    "publisher_bid_modifier": {
        "values": [{
                "target": "msn-can",
                "cpc_modification": 1.5
            },
            {
                "target": "msn-can-home",
                "cpc_modification": 1.5
            }
        ]
    }
}

The print(temp) in the code below will return: 以下代码中的print(temp)将返回:

[{"target": "msn-can-home","cpc_modification": 0.5}, {"target": "msn-can","cpc_modification": 0.5}]

After that, I extract the data I want to modify from the db and match it with the data extracted from the JSON response. 之后,我从db中提取要修改的数据,并将其与从JSON响应中提取的数据进行匹配。

I can easily modify "cpc_modification" if the value of "target" exists in the db. 如果db中存在“target”的值,我可以轻松修改“cpc_modification”。 My problem is to be able to do something else when the "target" value doesn't exist in the response. 我的问题是当响应中不存在“目标”值时能够做其他事情。

Here is what I've done so far: 这是我到目前为止所做的:

print(temp)

for dt in temp:
    theCursor.execute('SELECT ADJUST, SITE FROM SandboxPubTB WHERE CAMPAIGNNAME =?', (campaignName,) ) 
    campaignRows = theCursor.fetchall()
    for t in campaignRows:

        if t[1] == dt['target'] :
            dt['cpc_modification'] = "{:.2f}".format((int(t[0]) / 100) + 1)
            print("exists")
        #if dt['target'] not in t[1] :
        else:
            temp.append({'target': '"' + t[1] + "'", 'cpc_modification': "'" + str(t[0]) + "'"})
            print("Doesn't exists") 

print(temp) 

In the else I'm trying to append a new list entry with the new "target" and "cpc_modification" but the output is an infinite loop of the the print("Doesn't exists"). 在else中我试图用新的“target”和“cpc_modification”附加一个新的列表条目,但是输出是print的无限循环(“不存在”)。

The closest I came to the solution is this: 我最接近解决方案的是:

elif dt['target'] not in temp:

But this will iterate as many time as the number of entries in the temp list. 但是这将迭代临时列表中的条目数量。

To give an example with input and output: 举一个输入和输出的例子:

Input: 输入:

[{
    'target': 'msn-can',
    'cpc_modification': 1.5
}, {
    'target': 'msn-can-home',
    'cpc_modification': 1.5
}, {
    'target': 'foxnews-foxnews',
    'cpc_modification': 1.5
}, {
    'target': 'beachraider',
    'cpc_modification': 0.69
}, {
    'target': 'crowdyfan',
    'cpc_modification': 0.7
}, {
    'target': 'novelodge',
    'cpc_modification': 0.75
}, {
    'target': 'foxnews-androidapp',
    'cpc_modification': 0.5
}, {
    'target': 'foxnews-foxbusiness',
    'cpc_modification': 1.12
}, {
    'target': 'foxnews-iosapp',
    'cpc_modification': 0.86
}, {
    'target': 'thehindu-hindunews',
    'cpc_modification': 0.7
}, {
    'target': 'vitaminnews',
    'cpc_modification': 1.46
}]

Database: 数据库:

在此输入图像描述

Output: 输出:

[{
    'target': 'msn-can',
    'cpc_modification': 0.5 <----
}, {
    'target': 'msn-can-home',
    'cpc_modification': 0.5 <----
}, {
    'target': 'foxnews-foxnews',
    'cpc_modification': 1.5
}, {
    'target': 'beachraider',
    'cpc_modification': 0.69
}, {
    'target': 'crowdyfan',
    'cpc_modification': 0.7
}, {
    'target': 'novelodge',
    'cpc_modification': 0.75
}, {
    'target': 'foxnews-androidapp',
    'cpc_modification': 0.5
}, {
    'target': 'foxnews-foxbusiness',
    'cpc_modification': 1.12
}, {
    'target': 'foxnews-iosapp',
    'cpc_modification': 0.86
}, {
    'target': 'thehindu-hindunews',
    'cpc_modification': 0.7
}, {
    'target': 'vitaminnews',
    'cpc_modification': 1.46
}], {
    'target': 'msn-outlookcom-canada', <----
    'cpc_modification': 0.5 <----
}]

Your help will be much appreciated. 非常感谢您的帮助。 Thank you! 谢谢!

EDIT 编辑

The code above addresses only one campaign *campaignName variable", but the whole code should be able to treat more than one campaign. So here is an other example: 上面的代码只解决了一个广告系列* campaignName变量“,但整个代码应该可以处理多个广告系列。所以这是另一个例子:

input 输入

Campaign 1: 活动1:

[{
    'target': 'msn-can',
    'cpc_modification': 0.5
}, {
    'target': 'msn-can-home',
    'cpc_modification': 0.5
}]

Campaign 2: 活动2:

[{
    'target': 'fox-news',
    'cpc_modification': 0.9
}, {
    'target': 'fox-news-home',
    'cpc_modification': 0.6
}]

data in db db中的数据

Campaign 1: 活动1:

target: msn-can, cpc_modification: 7
target: msn-can-home, cpc_modification: 10

Campaign 2: 活动2:

target: fox-news, cpc_modification: 20
target: fox-news-home, cpc_modification: 30
target: msn-us, cpc_modification: 10

Output 产量

Campaign 1: 活动1:

[{
    'target': 'msn-can',
    'cpc_modification': 1.07
}, {
    'target': 'msn-can-home',
    'cpc_modification': 1.1
}]

Campaign 2: 活动2:

[{
    'target': 'fox-news',
    'cpc_modification': 1.2
}, {
    'target': 'fox-news-home',
    'cpc_modification': 1.3
}], {
    'target': 'msn-us',
    'cpc_modification': 1.1
}]

re-group your data so that you have a dictionary keyed by the target. 重新分组您的数据,以便您拥有由目标键入的字典。

rekey = {t['target']: t for t in temp}

then you can just look for your data naturally 那么你可以自然地查找你的数据

theCursor.execute('SELECT ADJUST, SITE FROM SandboxPubTB WHERE CAMPAIGNNAME =?', (campaignName,) ) 
campaignRows = theCursor.fetchall()
for t in campaignRows:
    fmt_value = "{:.2f}".format((int(t[0]) / 100) + 1)
    try:
        print(f"updating {t[1]}")
        rekey[t[1]]['cpc_modification'] = fmt_value
    except KeyError:
        print(f"Adding new key {t[1]}")
        rekey[t[1]] = {'target': t[1], 'cpc_modification': fmt_value}

from pprint import pprint
pprint(rekey.values())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM