0

我有两个字典:

blocked = {'-5.00': ['121', '381']}
all_odds = {'-5.00': '{"121":[1.85,1.85],"381":[2.18,1.73],"16":[2.18,1.61],"18":\
            [2.12,1.79]}'}

我想首先检查.keys()比较(==)是否返回True,这里它(两者-5.00)然后我想从中删除所有项目all_odds中列出的键blocked.values()

对于上述情况,它应该导致:

all_odds_final = {'-5.00': '{"16":[2.18,1.61],"18": [2.12,1.79]}'}

我试过for loop

if blocked.keys() == all_odds.keys():
    for value in blocked.values():
        for v in value:
            for val in all_odds.values():
                val = eval(val)
                if val.has_key(v):
                    del val[v] 

你知道这很丑陋,而且它还不能正常工作。

4

3 回答 3

1

首先,使字符串成为字典ast.literal_eval()不要使用eval()

>>> import ast
>>> all_odds['-5.00'] = ast.literal_eval(all_odds['-5.00'])

然后你可以使用字典理解:

>>> if blocked.keys() == all_odds.keys():
...     print {blocked.keys()[0] : {k:v for k, v in all_odds.values()[0].iteritems() if k not in blocked.values()[0]}}
... 
{'-5.00': {'18': [2.12, 1.79], '16': [2.18, 1.61]}}

但是,如果您希望将值-5.00作为字符串...

>>> {blocked.keys()[0]:str({k: v for k, v in all_odds.values()[0].iteritems() if k not in blocked.values()[0]})}
{'-5.00': "{'18': [2.12, 1.79], '16': [2.18, 1.61]}"}
于 2013-06-28T05:33:48.807 回答
1

这是您如何在大约 2 行中执行相同操作的方法。我不会在这里使用 ast 或 eval,但如果你想使用它,你可以添加它。

>>> blocked = {'-5.00': ['121', '381']}
>>> all_odds = {'-5.00': {'121':[1.85,1.85],'381':[2.18,1.73],'16':[2.18,1.61],'18':\
...      [2.12,1.79]}}
>>> bkeys = [k for k in all_odds.keys() if k in blocked.keys()]
>>> all_odds_final = {pk: {k:v for k,v in all_odds.get(pk).items() if k not in blocked.get(pk)} for pk in bkeys}
>>> all_odds_final
{'-5.00': {'18': [2.12, 1.79], '16': [2.18, 1.61]}}
于 2013-06-28T06:01:22.497 回答
1

这似乎有效:

blocked = {'-5.00': ['121', '381']}
all_odds = {'-5.00': {"121":[1.85,1.85],"381":[2.18,1.73],"16":[2.18,1.61],"18":\
        [2.12,1.79]}}
all_odds_final = dict(all_odds)
for key, blocks in blocked.iteritems():
    map(all_odds_final[key].pop,blocks,[])

如果您不想复制字典,则可以从原始 all_odds 字典中弹出项目:

for key, blocks in blocked.iteritems():
    map(all_odds[key].pop,blocks,[])

map 函数中的空列表是如此 pop 被调用 None 作为它的第二个参数。没有它 pop 只会得到一个参数,如果键不存在将返回错误。

于 2013-06-28T06:35:39.783 回答