第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

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

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

眼眸繁星 2022-07-12 15:26:30
我有一個(gè)字符串'request.context.user_id',我想用'。'分割字符串 并將列表中的每個(gè)元素用作字典鍵。有沒有辦法對(duì)不同長度的列表執(zhí)行此操作,而無需在拆分后嘗試對(duì)所有不同可能的列表長度進(jìn)行硬編碼?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 是應(yīng)由 x[parts[0]][parts[1] 檢索的字符串值列表 logData 是通過讀取 json 文件獲得的列表,然后可以使用 json_normalize 將列表讀入數(shù)據(jù)幀...提供了 df 部分以提供有關(guān)其結(jié)構(gòu)的一些上下文.. 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貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超5個(gè)贊

我剛剛在評(píng)論中意識(shí)到您說您不想創(chuàng)建新字典,而是x通過鏈接列表中的部分來訪問現(xiàn)有字典。


(3.b) 使用 afor loop獲取/設(shè)置路徑鍵中的值

如果您只想讀取路徑末尾的值


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 是您的案例的結(jié)果,string.slit('.')并且dict_是x字典。您可以省略copy.deepcopy()部分,這只是像我這樣偏執(zhí)的窺視者 - 原因是 python dict 不是不可變的,因此處理deepcopy(內(nèi)存中單獨(dú)但精確的副本)是一種解決方案。

set_val()正如我所說,這不是我的主意,@Bakuriu

dict.setdefault(key, default_value)的功勞將處理x.

eval()(3) 使用和/或?qū)⒆址u(píng)估為代碼exec()

所以這是一個(gè)丑陋的不安全解決方案:


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字典的最里面的值


我假設(shè)你可以像這樣在你的代碼中使用它


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()如果您想寫入,您可以使用將字符串作為代碼執(zhí)行x,盡管它同樣骯臟且不安全。


exec("x{} = '...or this, maybe?'".format(chained_keys))

print(x)


# will print

{'request': {'context': {'user_id': '...or this, maybe?'}}}

(2)一個(gè)實(shí)際的解決方案 可能是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方案 并將列表中的每個(gè)元素用作字典鍵

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


查看完整回答
反對(duì) 回復(fù) 2022-07-12
?
慕尼黑8549860

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超11個(gè)贊

如果您想要任意計(jì)數(shù),這意味著您需要一個(gè)循環(huán)。您可以get重復(fù)使用來鉆取字典層。


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


查看完整回答
反對(duì) 回復(fù) 2022-07-12
  • 2 回答
  • 0 關(guān)注
  • 216 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)