简体   繁体   English

遍历嵌套字典

[英]Iterate through nested dictionary

Im trying to create a function increase_by_one which takes in a dictionary and modifies the dictionary by increasing all values in it by 1. The function should remain all keys unchanged and finally return the modified dictionary. 我试着去创建一个函数increase_by_one这需要在一个字典,由1提高它的所有值的功能保持所有按键不变,最后返回修改后的字典修改字典。 If the dictionary is empty, return it without changing. 如果字典为空,则不做任何更改就将其返回。 (Dictionaries can be nested) (字典可以嵌套)

eg 例如

increase_by_one({'1':2.7, '11':16, '111':{'a':5, 't':8}})

would give 会给

{'1': 3.7, '11': 17, '111': {'a': 6, 't': 9}}

Im not sure how to do it for multiple(and unknown of number) nested dicitionaries. 我不确定如何对多个(但数量未知)嵌套字典进行操作。 Thank you. 谢谢。 Would prefer the code to be as simple as possible 希望代码尽可能简单

This is a simple way to solve the problem using recursion and dict comprehension: 这是使用递归和dict理解来解决问题的简单方法:

def increase_by_one(d):
    try:
        return d + 1
    except:
        return {k: increase_by_one(v) for k, v in d.items()}

In case there are values contained in the dict apart from numbers which can be added or other dictionaries, further type checking might be necessary. 如果字典中包含可以添加的数字或其他字典之外的值,则可能需要进一步的类型检查。

Assuming the values are either a number or a dictionary, you could consider: 假设值是数字或字典,则可以考虑:

def increase_by_one(d):
  for key in d:
    if type(d[key])==dict:
      d[key] = increase_by_one(d[key])
    else:
      d[key] += 1
  return d

For you input: 为您输入:

print(increase_by_one({'1':2.7, '11':16, '111':{'a':5, 't':8}}))

I got: 我有:

{'1': 3.7, '11': 17, '111': {'a': 6, 't': 9}}
def increase_by_one(d):
  for key in d:
    try:
      d[key] += 1
    except:  # cannot increase, so it's not a number
      increase_by_one(d[key])
  return d  # only necessary because of spec
def increase_by_one(dictio):
    for d in dictio:
        if isinstance(dictio[d], int) or isinstance(dictio[d], float):
            dictio[d] += 1
        else:
            increase_by_one(dictio[d])
    return dictio

increase_by_one({'1':2.7, '11':16, '111':{'a':5, 't':8}})

Using recurrence 使用重复

In-place modification of dict: 字典的就地修改:

def increase_by_one(my_dict):
    for k, v in my_dict.items():
        if any(isinstance(v, x) for x in (float, int)):
            my_dict.update({k: v + 1})
        elif isinstance(v, dict):
            my_dict.update({k: increase_by_one(v)})
    return my_dict

v = {'1': 2.7, '11': 16, '111': {'a': 5, 't': 8}}
print(increase_by_one(v))  # prints: {'111': {'a': 6, 't': 9}, '1': 3.7, '11': 17}

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

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