将字典值从列表转换为字典

2024-09-15 17:42:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数

dict1 = {'2132': [{'L': {'Y': '452.2'}}, {'L': {'N': '21'}}], '2345': [{'L': {'Y': '87'}}, {'C': {'N': '56'}}, {'6': {'Y': '45.23'}}]

我还有一个函数,我需要将dict1中的2132,L,Y值作为参数传递,结果应该是452.2

def getx(a, b, c):
    try:
        return dict1[a][b][c]
    except:
        return None

当我给出dict1['2132']结果[{'L': {'Y': '452.2'}}, {'L': {'N': '21'}}]

我想dict1['2132']['L']['Y']结果应该是452.2

所以我需要我的字典

dict1 = {'2132': [{'L': {'Y': '452.2'}}, {'L': {'N': '21'}}], '2345': [{'L': {'Y': '87'}}, {'C': {'N': '56'}}, {'6': {'Y': '45.23'}}]

显示为

dict1 = {'2132': {{'L': {'Y': '452.2'}}, {'L': {'N': '21'}}}, '2345': {{'L': {'Y': '87'}}, {'C': {'N': '56'}}, {'6': {'Y': '45.23'}}}

或者当dict1为空时,有没有其他方法可以拉取第四个值

dict1 = {'2132': [{'L': {'Y': '452.2'}}, {'L': {'N': '21'}}], '2345': [{'L': {'Y': '87'}}, {'C': {'N': '56'}}, {'6': {'Y': '45.23'}}]

Tags: 方法函数nonereturn字典deftryexcept
2条回答

这个怎么样:

from collections import defaultdict
for key,values in dict1.items():
    temp_dict = defaultdict(dict)
    for val in values: #values is a list of dict
        for k,v in val.items():
            temp_dict[k].update(v)
    dict1[key] = dict(temp_dict)
print(dict1)
#{'2132': {'L': {'Y': '452.2', 'N': '21'}}, '2345': {'L': {'Y': '87'}, 'C': {'N': '56'}, '6': {'Y': '45.23'}}}

然后呢

def getx(a, b, c):
    try:
        return dict1[a][b][c]
    except:
        return None
print(getx('2132','L','Y'))
#452.2

这是你的解决办法

#v1='2132' v2='L' v3='Y'
def Solution(v1,v2,v3):
    if v1 in dict1.keys():
        for i in dict1[v1]:
            if v2 in i.keys():
                if v3 in i[v2]:
                    return i[v2][v3]
    return None

dict1 = {'2132': [{'L': {'Y': '452.2'}}, {'C': {'N': '21'}}], '2345': [{'L': {'Y': '87'}}, {'C': {'N': '56'}},{'6': {'Y': '45.23'}}]}
print(Solution('2132','L','Y'))

相关问题 更多 >