亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在python中將字符串列表拆分為字典鍵

在python中將字符串列表拆分為字典鍵

眼眸繁星 2022-07-12 15:26:30
我有一個字符串'request.context.user_id',我想用'。'分割字符串 并將列表中的每個元素用作字典鍵。有沒有辦法對不同長度的列表執行此操作,而無需在拆分后嘗試對所有不同可能的列表長度進行硬編碼?parts = string.split('.')if len(parts)==1:    data = [x for x in logData if x[parts[0]] in listX]elif len(parts)==2:    data = [x for x in logData if x[parts[0]][parts[1]] in listX]else:    print("Add more hard code")listX 是應由 x[parts[0]][parts[1] 檢索的字符串值列表 logData 是通過讀取 json 文件獲得的列表,然后可以使用 json_normalize 將列表讀入數據幀...提供了 df 部分以提供有關其結構的一些上下文.. dicts 列表:import jsonfrom pandas.io.json import json_normalizewith open(project_root+"filename") as f:    logData = json.load(f)df = json_normalize(logData)
查看完整描述

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


查看完整回答
反對 回復 2022-07-12
?
慕尼黑8549860

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']


查看完整回答
反對 回復 2022-07-12
  • 2 回答
  • 0 關注
  • 210 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號