5 回答

TA貢獻(xiàn)1886條經(jīng)驗 獲得超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}}

TA貢獻(xiàn)1847條經(jīng)驗 獲得超11個贊
這可能最好通過 完成collections.defaultdict,但這需要導(dǎo)入。
不導(dǎo)入的另一種方法可能是:
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,那么您可能需要將代碼中的相關(guān)行更改為:
outer_key = to_slice[:-1]
inner_key = to_slice[-1]

TA貢獻(xiàn)1794條經(jīng)驗 獲得超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)

TA貢獻(xiàn)1797條經(jīng)驗 獲得超4個贊
此代碼假設(shè)要轉(zhuǎn)換為鍵的列表元素始終具有 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}}

TA貢獻(xiàn)1780條經(jīng)驗 獲得超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]如果可以有兩位數(shù),拆包部分會稍微復(fù)雜一點:
for (c, *n), m in nested_list:
n = ''.join(n)
...
FWIW,如果你被允許進口,我會用defaultdict(dict)
添加回答
舉報