我有两个词:
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()
中列出密钥的{1}}。
对于上述情况,应该导致:
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]
你知道它非常丑陋加上它还没有正常工作。
答案 0 :(得分:1)
首先,将字符串设为ast.literal_eval()
的字典。 Don't use 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]}"}
答案 1 :(得分: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]}}
答案 2 :(得分: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只会获得一个参数,并且如果该键不存在则会返回错误。