[英]Filtering dict of dict with dictionary comprehension
我在使用dict理解时过滤dict的dict时遇到问题。
我有命令:
clients = {
'Shop': {'url' : 'url_v', 'customer' : 'cumoster_v',
'some_other_key1' : 'some_value'},
'Gym': {'url' : 'url_v1', 'customer_1' : 'customer_v1', 'customer_2': 'customer_v2',
'some_other_key2' : 'some_value'},
'Bank': {'url' : 'url_v2', 'customer_3' : 'customer_v3',
'some_other_key3' : 'some_value'}
}
我想再做一个仅包含“ customer。*”键的字典。 因此,新字典应如下所示:
dict_only_cust = {
'Shop': {'customer' : 'cumoster_v'},
'Gym': {'customer_1' : 'customer_v1', 'customer_2': 'customer_v2'},
'Bank': {'customer_3' : 'customer_v3'}
}
因为我是列表和字典理解的忠实拥护者,所以我想知道是否可以这样做。
到目前为止,我已经写了:
dict_only_cust = {v.pop(t) for k, v in clients.items()
for t, vv in v.items()
if not re.match('.*customer.*', t)}
代码失败,出现'RuntimeError: dictionary changed size during iteration'
我第二次尝试:
dict_only_cust = {k:{t: vv} for k, v in clients.items()
for t, vv in v.items()
if re.match('.*customer.*', t)}
几乎可以,但是又回来了
dict_only_cust = {
'Shop' : {'customer' : 'cumoster_v'},
'Gym' : {'customer_1' : 'customer_v1'},
'Bank' : {'customer_3' : 'customer_v3'}
}
如何使用dict理解解决这个问题? 我正在使用python 3.4。
谢谢!
>>> {key:{k:v for k,v in dic.items() if 'customer' in k} for key,dic in clients.items()}
{'Shop': {'customer': 'cumoster_v'}, 'Gym': {'customer_2': 'customer_v2', 'customer_1': 'customer_v1'}, 'Bank': {'customer_3': 'customer_v3'}}
{k:{k1:v1 for k1,v1 in v.items() if k1.startswith('customer')} for k, v in clients.items()}
输出:
{'Shop': {'customer': 'cumoster_v'}, 'Gym': {'customer_2': 'customer_v2', 'customer_1': 'customer_v1'}, 'Bank': {'customer_3': 'customer_v3'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.