简体   繁体   English

Python 嵌套字典理解与 if else

[英]Python nested dict comprehension with if else

I am trying to convert the below to a dict comprehension我正在尝试将以下内容转换为字典理解

my_dict = {'a': None, 'b': None, 'c': ['1', '2', '3']}
new_dict = {}
 for k, v in my_dict.items():
     if not v:
         new_dict[k] = None
     else:
         for item in v:
             new_dict[f'{k}{item}'] = None

I'm trying to translate my dict to我正在尝试将我的字典翻译成

new_dict = {'a': None, 'b': None, 'c1': None, 'c2': None, 'c3': None}

I'm fairly comfortable with basic list and dict comprehensions but struggling with this one, currently looking something like this but clearly I am a bit off on the syntax:我对基本的列表和字典理解相当满意,但在这个方面很挣扎,目前看起来像这样,但显然我对语法有点偏离:

{k: None if not v else f'{k}{item}': None for item in v for k, v in my_dict.items()}

This abomination will do:这种可憎的行为会:

{fk: None
 for k, v in my_dict.items()
 for fk in ([k] if v is None else (k + fv for fv in v))}

If the value is None , you just want the key.如果值为None ,您只需要密钥。
If the value is not None , you want a list of each value concatenated with the key.如果该值不是None ,您需要一个与键连接的每个值的列表。
Homogenise that to always returning a list, either of one key or multiple:将其同质化为始终返回一个列表,一个键或多个:

[k] if v is None else [k + fv for fv in v]

Then you're looking at a "simple" nested comprehension:然后你正在看一个“简单”的嵌套理解:

{k: None for k in [['a'], ['b'], ['c1', 'c2', 'c3']] for fk in k}

I was proud of my answer:我为我的回答感到自豪:

new_dict = dict(
    sum(
        [
            [(k, None)] if not value else [(f"{k}{v}", None) for v in value]
            for k, value in my_dict.items()
        ],
        [],
    )
)

... until I saw deceze's answer, which I still need to digest. ...直到我看到 deceze 的回答,我仍然需要消化。

You can do this with the help of itertools.chain.from_iterable :你可以在itertools.chain.from_iterable的帮助下做到这一点:

>>> {
    y: None
    for y in itertools.chain.from_iterable(
            k if not v else (f"{k}{x}" for x in v) for k, v in my_dict.items()
        )
    }
{'a': None, 'b': None, 'c1': None, 'c2': None, 'c3': None}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM