gpt4 book ai didi

python - 如何更新未知状态的深度嵌套字典?

转载 作者:行者123 更新时间:2023-12-01 03:33:08 25 4
gpt4 key购买 nike

我有 3 级深度的字典。我不知道 key 是否存在。如果它们存在,我需要更新该值。如果它们不存在,我需要添加键和值。

这是我的代码...但很困惑。必须有一种更干净、更优雅的方法来做到这一点???

建议???

def update_balances_cache(client_name, exchange_name,
api_key_nickname, balances,
time_checked):

from settings import CACHE

'''
Dictionary structure:
balances = {client_name: {exchange_name: {api_key_nickname: {balances}
}
}
}

CACHE is a class instance holding shared variables between modules.

'''

api_key_level = {api_key_nickname: balances}

exchange_level = {exchange_name: api_key_level}


with CACHE.vlock:
try:
# is there a client in the dictionary?
CACHE.BALANCES_CACHE[client_name]
except:
# add client level to dictionary
CACHE.BALANCES_CACHE[client_name] = exchange_level
CACHE.BALANCES_CACHE[client_name][exchange_name][api_key_nickname]['last check time'] = time_checked

return

# there is a client in the dictionary. Is the exchange there?
try:
CACHE.BALANCES_CACHE[client_name][exchange_name]
except:
# add the exchange
CACHE.BALANCES_CACHE[client_name][exchange_name] = exchange_level
CACHE.BALANCES_CACHE[client_name][exchange_name][api_key_nickname]['last check time'] = time_checked

return

# there is a client & exchange.
CACHE.BALANCES_CACHE[client_name][exchange_name][api_key_nickname] = api_key_level
CACHE.BALANCES_CACHE[client_name][exchange_name][api_key_nickname]['last check time'] = time_checked

return

最佳答案

试试这个

def updatedict(a,b):
for key in b:
if not key in a or type(a[key]) != dict or type(b[key])!=dict:
a[key]=b[key]
else:
updatedict(a[key],b[key])
x={"a":{"b":{"c":"d"}}}
y={"a":{"b":{"e":"f","c":"d1"},"g":{"h":"i"}},"j":{"k":{"l":"m"}}}
updatedict(x,y)
print(x)

更新后的 x 值

{'j': {'k': {'l': 'm'}}, 'a': {'b': {'c': 'd1', 'e': 'f'}, 'g': {'h': 'i'}}}

关于python - 如何更新未知状态的深度嵌套字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40648302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com