【问题标题】:Python dictionary iterating over nested dictionaries for a particular operation/functionPython 字典为特定操作/功能迭代嵌套字典
【发布时间】:2017-04-05 04:19:28
【问题描述】:

如果我有一个必须为字典中的嵌套字典执行的函数。那我应该怎么执行呢?

例如:

# I have the below dictionary
d = {'a':1, 'b':2, 'c':3, 'd': {'e':4, 'f':5}}

# I wanted a result as below
{'a': 1, 'b': 2, 'c': 3, 'e': 4, 'f': 5}

#I have executed it by 

for i, j in d.items():

    if type(j) == dict:
        for key,value in d[i].items():
            d[key] = value
        d.pop(i, None)

print d

#output
{'a': 1, 'c': 3, 'b': 2, 'e': 4, 'f': 5}

但是如果有很多嵌套字典怎么办?我对此有点困惑?有什么建议吗?

提前致谢。

【问题讨论】:

  • 递归调用?
  • @bharadhwaj 是的

标签: python dictionary


【解决方案1】:

我建议这是一种扁平化形式:

def flatten(d):
    es = [d.pop(k) for k in sorted(d) if isinstance(d[k], dict)]
    # Due to sorted the dictionaries those keys that are lexicographically after 
    # will overwrite the key-value pairs from those that are before.

    # One would expect that `d.update(*es)` would work 
    # but it doesn't as `update` only takes one argument.
    for e in es:
        d.update(e)

def flatten_many(d):
    while any(isinstance(d[k], dict) for k in d):
        flatten(d)

第一个函数从d 中弹出每个字典,然后用它们更新d。第二个函数应用flatten 第一个函数,而有一个值是字典。

【讨论】:

  • 谢谢 .. 它让我了解了嵌套字典的递归函数。我会多练习。 :)
  • Dan D. 的答案中没有任何内容是递归的(自调用)。一切都是迭代的,因为 flatten() 在 flatten_many() 的 while 循环中被调用。
  • @ChristianKönig 但我认为 pop 函数在这里递归执行。如果我错了,请纠正我。
  • 重复不同于递归。请看一下例如wikipedia详细解释。
【解决方案2】:
dd={}
def myprint(d):
     for k, v in d.iteritems():
         if isinstance(v, dict):
             myprint(v)
         else:
             dd.update({k:v})
     return dd


d={'a':1, 'b':2, 'c':3, 'd': {'e':4, 'f':5,'g':{'h':6}}}
print(myprint(d))

输出- {'a': 1, 'c': 3, 'b': 2, 'e': 4, 'f': 5, 'h': 6}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 2022-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 2021-11-29
    相关资源
    最近更新 更多