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

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

如何從python中的嵌套列表制作嵌套字典

如何從python中的嵌套列表制作嵌套字典

開心每一天1111 2022-11-24 14:56:23
基本上我有一個嵌套列表:nested_list = [['X1',5],['X2',6],['Y1',5],['Y2',6]]我想要這本字典:nested_dictionary = {'X': {'1':5, '2':6},'Y':{'1':5,'2':6}}有誰知道如何解決這個問題?有些人通過導入來做到這一點,但我正在尋找無需導入的解決方案
查看完整描述

5 回答

?
MM們

TA貢獻1886條經驗 獲得超2個贊

嘗試:


nested_list = [['X1', 5], ['X2', 6], ['Y1', 5], ['Y2', 6]]

nested_dict = {}

for sublist in nested_list:

    outer_key = sublist[0][0]

    inner_key = sublist[0][1]

    value = sublist[1]

    if outer_key in nested_dict:

        nested_dict[outer_key][inner_key] = value

    else:

        nested_dict[outer_key] = {inner_key: value}


print(nested_dict)

# output: {'X': {'1': 5, '2': 6}, 'Y': {'1': 5, '2': 6}}


查看完整回答
反對 回復 2022-11-24
?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

這可能最好通過 完成collections.defaultdict,但這需要導入。


不導入的另一種方法可能是:


nested_list = [['X1',5],['X2',6],['Y1',5],['Y2',6]]


final_dict = {}


for to_slice, value in nested_list:

    outer_key = to_slice[0]

    inner_key = to_slice[1:]


    if outer_key not in final_dict:

        final_dict[outer_key] = {}


    final_dict[outer_key][inner_key] = value


print(final_dict)

這假定外鍵始終是to_slice. 但是如果外鍵是 中的最后一個字符to_slice,那么您可能需要將代碼中的相關行更改為:


outer_key = to_slice[:-1]

inner_key = to_slice[-1]


查看完整回答
反對 回復 2022-11-24
?
幕布斯7119047

TA貢獻1794條經驗 獲得超8個贊

dict={}

key =[]

value = {}

for item in nested_list:

  for i in item[0]:

    if i.isalpha() and i not in key :

      key.append(i)

    if i.isnumeric():

     value[i]=item[1]


for k in key:

  dict[k]= value


print(dict)


查看完整回答
反對 回復 2022-11-24
?
繁星coding

TA貢獻1797條經驗 獲得超4個贊

此代碼假設要轉換為鍵的列表元素始終具有 2 個字符。


nested_list = [['X1',5],['X2',6],['Y1',5],['Y2',6]]

nested_dictionary = {}

for item in nested_list:

  if not item[0][0] in nested_dictionary: # If the first letter isn't already in the dictionary

    nested_dictionary[item[0][0]] = {} # Add a blank nested dictionary

  nested_dictionary[item[0][0]][item[0][1]] = item[1] # Set the value

print(nested_dictionary)

輸出:


{'X': {'1': 5, '2': 6}, 'Y': {'1': 5, '2': 6}}


查看完整回答
反對 回復 2022-11-24
?
翻閱古今

TA貢獻1780條經驗 獲得超5個贊

使用嵌套解包 and dict.setdefault,您可以很容易地完成此操作:


d = {}

for (c, n), i in nested_list:

    d_nested = d.setdefault(c, {})

    d_nested[n] = i


print(d)  # -> {'X': {'1': 5, '2': 6}, 'Y': {'1': 5, '2': 6}}

nested_list[x][0]如果可以有兩位數,拆包部分會稍微復雜一點:


for (c, *n), m in nested_list:

    n = ''.join(n)

    ...

FWIW,如果你被允許進口,我會用defaultdict(dict)


查看完整回答
反對 回復 2022-11-24
  • 5 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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