从字典词典中提取值

Roh*_*mar 0 python dictionary python-3.x

我有一本字典A:

A = {"'Delhi-Mumbai'": {6: [3]}, "'Doon-Gurgaon'": {8: [6, 9, 8, 5], 6: [7, 1, 2]}}
Run Code Online (Sandbox Code Playgroud)

我想从中提取数据,以便最终得到

extracted = {"'Delhi-Mumbai'": 6, "'Doon-Gurgaon'": [8,6]}
Run Code Online (Sandbox Code Playgroud)

我尝试运行此

for k,v in A.items():
    for i,j in v.items():
        new[k]=i
Run Code Online (Sandbox Code Playgroud)

但是此代码仅返回:

{"'Delhi-Mumbai'": 6, "'Doon-Gurgaon'": 6}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

hir*_*ist 6

这是一个简单的选择:

res = {key: list(value) for key, value in A.items()}
Run Code Online (Sandbox Code Playgroud)

如果要在同一行中固定双引号,则可以使用以下命令:

res = {key[1:-1]: list(value) for key, value in A.items()}
# {'Delhi-Mumbai': [6], 'Doon-Gurgaon': [8, 6]}
Run Code Online (Sandbox Code Playgroud)

在这里,我只是剥离每个字符串的第一个和最后一个字符。


在您的解决方案中,您new[k] = i将为每个新覆盖i。这样,仅剩下最后一个。