簡體   English   中英

如何從 function 返回嵌套字典

[英]How to return nested dictionary from function

是否可以制作一個 function ,它將根據 arguments 返回一個嵌套的字典?

def foo(key):
    d = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}, }
    return d[key]

foo(['c']['d']) 

我在等待:

3

我越來越:

TypeError: list indices must be integers or slices, not str

我了解可以返回整個字典,或對其進行硬編碼以返回字典的特定部分,例如

if 'c' and 'd' in kwargs:
    return d['c']['d']
elif 'c' and 'e' in kwargs:
        return d['c']['e']

但它會非常不靈活

當您給出['c']['d']時,您使用字母d對列表['c']進行切片,這是不可能的。 所以你可以做的是,更正切片:

foo('c')['d']

或者你可以改變你的 function 來切片它:

def foo(*args):
    d = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}, }
    d_old = dict(d) # if case you have to store the dict for other operations in the fucntion
    for i in args:
        d = d[i]
    return d
>>> foo('c','d')
3
d = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}, }
def funt(keys):
  val = d
  for key in keys:
    if val:
      val = val.get(key)
  return val

funt(['c', 'd'])

另外要處理不存在的密鑰 state。

一種可能的解決方案是迭代多個鍵 -

def foo(keys, d=None):
    if d is None:
        d = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}, }
    if len(keys) == 1:
        return d[keys[0]]
    return foo(keys[1:], d[keys[0]])

foo(['c', 'd']) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM