3 回答

TA貢獻1848條經(jīng)驗 獲得超10個贊
這對我有用
def sprintLog(sprnt):
new_dict = {}
new_dict = {x: {y: sprnt[y][x] for y in sprnt.keys() if x in sprnt[y]} for l in sprnt.values() for x in l}
return new_dict
print(sprintLog({'Ben': {'task1': 5}, 'alex': {'task1': 10, 'task2': 4}}))

TA貢獻1858條經(jīng)驗 獲得超8個贊
即使上面的列表理解答案是正確的,我還是會滑動這個答案以便更好地理解:)
from collections import defaultdict
def sprintLog(sprnt): # d = {'Ben': {'task1': 5}, 'alex': {'task1': 10, 'task2': 4}}
new_dict = defaultdict(dict)
for parent in sprnt.keys():
for sub_parent in sprnt[parent].keys():
new_dict[sub_parent][parent] = sprnt[parent][sub_parent]
return new_dict
a = sprintLog({'Ben': {'task1': 5}, 'alex': {'task1': 10, 'task2': 4}})
print(a)

TA貢獻1806條經(jīng)驗 獲得超8個贊
我想這就是你要找的:
d = {'Ben': {'task1': 5}, 'alex': {'task1': 10, 'task2': 4}}
def sprintLog(sprnt):
return {x: {y: f[x] for y,f in sprnt.items() if x in sprnt[y]} for l in sprnt.values() for x in l}
print(sprintLog(d))
您也需要使用sprnt.items()而不是sprnt.keys()so 來獲取值。
添加回答
舉報