使用列表搜索词典并创建新词典

时间:2019-08-07 19:17:54

标签: python

努力弄清楚这一点。我有这样的字典:

pprint(mydict)
{'bob': {'address': '1 bob place, bobtown', 'fullname': 'Boby McBoberton'},
 'fred': {'address': '1 fred place, fredtown', 'fullname': 'Freddy Frederton'},
 'john': {'address': '1 john place, johntown', 'fullname': 'John McJonerton'}}

然后,我有一个用户名列表,如下所示:

print(admins)
['bob', 'fred']

我需要做的是使用admins中的名称并搜索mydict,然后仅用名称和地址创建一个新字典。

因此最终结果应类似于:

{'bob': {'address': '1 bob place, bobtown'},
 'fred': {'address': '1 fred place}},

任何指针?

4 个答案:

答案 0 :(得分:1)

使用这样的字典理解

>>> d = {'bob': {'fullname': 'Boby McBoberton', 'address': '1 bob place, bobtown'}, 'john': {'fullname': 'John McJonerton', 'address': '1 john place, johntown'}, 'fred': {'fullname': 'Freddy Frederton', 'address': '1 fred place, fredtown'}}
>>> admins = ['bob', 'fred']
>>> 
>>> {k:dict(address = d[k]['address']) for k in admins}
{'bob': {'address': '1 bob place, bobtown'}, 'fred': {'address': '1 fred place, fredtown'}}

答案 1 :(得分:0)

类似的东西:

next_dict = {key, mydict[key]['address'] for key in (mydict.keys() & set(admins))}

答案 2 :(得分:0)

尝试:

out_dict = {}

for admin in admins:
    if admin in mydict.keys():
        out_dict[admin] = {'address': mydict[admin]['address']} 

答案 3 :(得分:0)

  1. 遍历admins列表
  2. 如果在original_dict中找到了管理员,请将其添加到final_dict

这样,如果original_dict中没有管理员,则代码不会中断。 代码如下:

original_dict= {'bob': {'address': '1 bob place, bobtown', 'fullname': 'Boby McBoberton'},
                 'fred': {'address': '1 fred place, fredtown', 'fullname': 'Freddy Frederton'},
                 'john': {'address': '1 john place, johntown', 'fullname': 'John McJonerton'}}
admins = ['bob','fred','pavan']
final_dict = {}
for admin in admins:
    if admin in original_dict:
        final_dict[admin] = {original_dict[admin]['address']}
print (final_dict)