簡體   English   中英

遍歷嵌套字典

[英]Iterate through nested dictionary

我試着去創建一個函數increase_by_one這需要在一個字典,由1提高它的所有值的功能保持所有按鍵不變,最后返回修改后的字典修改字典。 如果字典為空,則不做任何更改就將其返回。 (字典可以嵌套)

例如

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

會給

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

我不確定如何對多個(但數量未知)嵌套字典進行操作。 謝謝。 希望代碼盡可能簡單

這是使用遞歸和dict理解來解決問題的簡單方法:

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

如果字典中包含可以添加的數字或其他字典之外的值,則可能需要進一步的類型檢查。

假設值是數字或字典,則可以考慮:

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

為您輸入:

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

我有:

{'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}})

使用重復

字典的就地修改:

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