有没有办法在Python中替换嵌套字典中的None值?

huangapple go评论67阅读模式
英文:

Is there a way to replace None in nested Dictionary in python

问题

我想检查是否有一种方法可以在Python中替换嵌套字典中的None。例如,这是我下面有的字典

dict = {1 : {'Geeks' : [[1, "N", None]], 'Geeks1' : [[1, None, "H"]]}}

我们可以在这里用0替换None吗?

英文:

I wanted to check if there a way to replace None in nested Dictionary in python. For example, this is the dict in have below

dict = {1 : {'Geeks' : [[1, "N", None]], 'Geeks1' : [[1, None, "H"]]}}

Can we replace None with 0 here?

答案1

得分: 1

你可以尝试使用类似这样的字典推导式:

updated_dict = {key: {inner_key: [[x if x is not None else 0 for x in inner_list] for inner_list in inner_value] for inner_key, inner_value in value.items()} for key, value in your_dict.items()}

这将打印出:

{1: {'Geeks': [[1, 'N', 0]], 'Geeks1': [[1, 0, 'H']]}}

通常情况下,通过使用列表推导式和条件语句,我们遍历了字典的嵌套结构,并检查了列表中的每个元素。如果元素为None,则替换为0。


如果你希望进行原地替换,你可以尝试这样做:

your_dict = {1: {'Geeks': [[1, "N", None]], 'Geeks1': [[1, None, "H"]]}}
for inner_list in your_dict.values():
    for lst in inner_list.values():
        for i, item in enumerate(lst):
            if item is None:
                lst[i] = 0

这将输出与上述解决方案相同的字典。

英文:

You could try a dictionary comprehension like this:

updated_dict = {key: {inner_key: [[x if x is not None else 0 for x in inner_list] for inner_list in inner_value] for inner_key, inner_value in value.items()} for key, value in your_dict.items()}

which would print as:

{1: {'Geeks': [[1, 'N', 0]], 'Geeks1': [[1, 0, 'H']]}}

In general, by using list comprehensions and conditionals, we traverse the nested structure of the dictionary and check each element within the lists. If an element is None, it is replaced with 0.


If you wish to do the replacement in-place, then you could try this:

your_dict = {1: {'Geeks': [[1, "N", None]], 'Geeks1': [[1, None, "H"]]}}
for inner_list in your_dict.values():
    for lst in inner_list.values():
        for i, item in enumerate(lst):
            if item is None:
                lst[i] = 0

which outputs the same dictionary as the above solution.

huangapple
  • 本文由 发表于 2023年6月19日 17:24:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76505286.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定