本文介绍了用字典理解过滤字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用dict理解时过滤dict的字典时遇到问题。
I have problem with filtering dict of dict while using dict comprehension.
我有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。*键的字典。 因此,新字典应该像这样:
I would like to make another dict which will have only 'customer.*' keys. So, new dict should looks like:
dict_only_cust = { 'Shop': {'customer' : 'cumoster_v'}, 'Gym': {'customer_1' : 'customer_v1', 'customer_2': 'customer_v2'}, 'Bank': {'customer_3' : 'customer_v3'} }由于我是列表和字典理解的忠实拥护者,我想知道
As I'm big fan of lists and dicts comprehension, I'm wondering if it is possible to do it with this.
到目前为止,我已经写过:
So far, I've written:
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:词典在迭代过程中更改了大小'
第二次尝试:
dict_only_cust = {k:{t: vv} for k, v in clients.items() for t, vv in v.items() if re.match('.*customer.*', t)}这几乎可以,但是正在返回
It is almost OK, but it is returning
dict_only_cust = { 'Shop' : {'customer' : 'cumoster_v'}, 'Gym' : {'customer_1' : 'customer_v1'}, 'Bank' : {'customer_3' : 'customer_v3'} }如何解决使用dict理解会出现此问题吗? 我正在使用python 3.4。
How to solve this problem using dict comprehension? I'm using 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'}}
更多推荐
用字典理解过滤字典
发布评论