我想在字典中的字典中列印數字:
frame = ['frame1', 'frame2', 'frame3', 'frame4', 'frame5', 'frame6']
dx = [12, 34, 55, 66, 78, 65, 56, 234, 876, 999, 345, 945]
pd = ['pd1', 'pd2']
data = {}
dt = {}
k=0
for i in pd :
dt[i] = []
for j in frame :
data[j] = dt
data[j][i] = dx[k]
k =1
對于此代碼,它僅傳遞最后一個值:
{'frame1': {'pd1': 65, 'pd2': 945}, 'frame2': {'pd1': 65, 'pd2': 945}, 'frame3': {'pd1': 65, 'pd2': 945}, 'frame4': {'pd1': 65, 'pd2': 945}, 'frame5': {'pd1': 65, 'pd2': 945}, 'frame6': {'pd1': 65, 'pd2': 945}}
這是我想要的結果:
{'frame1': {'pd1': 12, 'pd2': 56}, 'frame2': {'pd1': 34, 'pd2': 234}, 'frame3': {'pd1': 55, 'pd2': 876}, 'frame4': {'pd1': 66, 'pd2': 999}, 'frame5': {'pd1': 78, 'pd2': 345}, 'frame6': {'pd1': 65, 'pd2': 945}}
uj5u.com熱心網友回復:
看起來所有字典都有一些共享記憶體。
您可以使用字典推導來構造字典:
{f: dict(zip(pd, vals)) for f, vals in zip(frame, zip(dx[:len(dx)//2], dx[len(dx)//2:]))}
這輸出:
{
'frame1': {'pd1': 12, 'pd2': 56}, 'frame2': {'pd1': 34, 'pd2': 234},
'frame3': {'pd1': 55, 'pd2': 876}, 'frame4': {'pd1': 66, 'pd2': 999},
'frame5': {'pd1': 78, 'pd2': 345}, 'frame6': {'pd1': 65, 'pd2': 945}
}
uj5u.com熱心網友回復:
這應該作業
data = {}
k=0
for i in pd:
for j in frame :
# use setdefault to initialize inner dictionary
data.setdefault(j, {})[i] = dx[k]
k =1
data
{'frame1': {'pd1': 12, 'pd2': 56},
'frame2': {'pd1': 34, 'pd2': 234},
'frame3': {'pd1': 55, 'pd2': 876},
'frame4': {'pd1': 66, 'pd2': 999},
'frame5': {'pd1': 78, 'pd2': 345},
'frame6': {'pd1': 65, 'pd2': 945}}
uj5u.com熱心網友回復:
可能有點長:
{f: d for f, d in zip(frame, {pd[0]: i, pd[1]: j} for i, j in zip(dx[:len(frame)], dx[len(frame):]))}
但是可以稍微簡化一下:
dict(zip(frame, (dict(zip(pd, x)) for x in zip(dx[:len(frame)], dx[len(frame):]))))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/477410.html
標籤:Python python-3.x 字典
