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

时间:2019-10-05 05:39:08

标签: python python-3.x

我有一个产生结果的函数

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为

时,还有其他方法可以拉出第4个值。
dict1 = {'2132': [{'L': {'Y': '452.2'}}, {'L': {'N': '21'}}], '2345': [{'L': {'Y': '87'}}, {'C': {'N': '56'}}, {'6': {'Y': '45.23'}}]

2 个答案:

答案 0 :(得分:0)

如何?

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

答案 1 :(得分:0)

这是您的解决方案

#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'))