用字典理解过滤字典

编程入门 行业动态 更新时间:2024-10-24 14:25:51
本文介绍了用字典理解过滤字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在使用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'}}

更多推荐

用字典理解过滤字典

本文发布于:2023-11-26 03:12:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632405.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:用字   字典

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!