2 回答

TA貢獻1851條經驗 獲得超5個贊
我剛剛在評論中意識到您說您不想創建新字典,而是x通過鏈接列表中的部分來訪問現有字典。
(3.b) 使用 afor loop獲取/設置路徑鍵中的值
如果您只想讀取路徑末尾的值
import copy
def get_val(key_list, dict_):
reduced = copy.deepcopy(dict_)
for i in range(len(key_list)):
reduced = reduced[key_list[i]]
return reduced
# this solution isn't mine, see the link below
def set_val(dict_, key_list, value_):
for key in key_list[:-1]:
dict_ = dict_.setdefault(key, {})
dict_[key_list[-1]] = value_
get_val() 其中 key_list 是您的案例的結果,string.slit('.')并且dict_是x字典。您可以省略copy.deepcopy()部分,這只是像我這樣偏執的窺視者 - 原因是 python dict 不是不可變的,因此處理deepcopy(內存中單獨但精確的副本)是一種解決方案。
set_val()正如我所說,這不是我的主意,@Bakuriu
dict.setdefault(key, default_value)的功勞將處理x.
eval()(3) 使用和/或將字符串評估為代碼exec()
所以這是一個丑陋的不安全解決方案:
def chainer(key_list):
new_str = ''
for key in key_list:
new_str = "{}['{}']".format(new_str, key)
return new_str
x = {'request': {'context': {'user_id': 'is this what you are looking for?'}}}
keys = 'request.context.user_id'.split('.')
chained_keys = chainer(keys)
# quite dirty but you may use eval() to evaluate a string
print( eval("x{}".format(chained_keys)) )
# will print
is this what you are looking for?
這是模型x字典的最里面的值
我假設你可以像這樣在你的代碼中使用它
data = [x for x in logData if eval("x{}".format(chained_keys)) in listX]
# or in python 3.x with f-string
data = [x for x in logData if eval(f"x{chained_keys}") in listX]
...或類似的東西。
類似地,exec()如果您想寫入,您可以使用將字符串作為代碼執行x,盡管它同樣骯臟且不安全。
exec("x{} = '...or this, maybe?'".format(chained_keys))
print(x)
# will print
{'request': {'context': {'user_id': '...or this, maybe?'}}}
(2)一個實際的解決方案 可能是recursive function這樣的:
def nester(key_list):
if len(key_list) == 0:
return 'value' # can change this to whatever you like
else:
return {key_list.pop(0): nester(key_list)}
keys = 'request.context.user_id'.split('.')
# ['request', 'context', 'user_id']
data = nester(keys)
print(data)
# will result
{'request': {'context': {'user_id': 'value'}}}
(1)用'.'分割字符串的解決list comprehension方案 并將列表中的每個元素用作字典鍵
data = {}
parts = 'request.context.user_id'.split('.')
if parts: # one or more items
[data.update({part: 'value'}) for part in parts]
print(data)
# the result
{'request': 'value', 'context': 'value', 'user_id': 'value'}
您可以在之后覆蓋這些值。data

TA貢獻1818條經驗 獲得超11個贊
如果您想要任意計數,這意味著您需要一個循環。您可以get重復使用來鉆取字典層。
parts = "request.context.user_id".split(".")
logData = [{"request": {"context": {"user_id": "jim"}}}]
listX = "jim"
def generate(logData, parts):
for x in logData:
ref = x
# ref will be, successively, x, then the 'request' dictionary, then the
# 'context' dictionary, then the 'user_id' value 'jim'.
for key in parts:
ref = ref[key]
if ref in listX:
yield x
data = list(generate(logData, parts))) # ['jim']
添加回答
舉報