I have problem with filtering dict of dict while using dict comprehension.
I have 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'}
}
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)}
Code fails with 'RuntimeError: dictionary changed size during iteration'
Second time I've tried:
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'}
}
How to solve this problem using dict comprehension? I'm using python 3.4.
Thanks!
>>> {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'}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.