首页 > 解决方案 > Python 解析字典

问题描述

我正在研究一个示例并坚持创建一个函数。该程序的目的是根据列表解析字典。我有一个列表“my_list”,其中包含“my_diction”字典的键。我想像那样解析字典(期望输出);

[5, 6, 7, 8]
[50, 60, 70, 80]
['K', 'L', 'M', 'N']
['X', 'Y']
['Z']

代码:

my_list = [5, 6, 7, 8]
my_diction = {5: (50, 'K', 'X'), 6: (60, 'L'), 7: (70, 'M', 'Y', 'Z'), 8: (80, 'N')}

def resolve_func(b_dict):
#
# `Resolving has to be done in here`
#
    return    

print('Resolved:')
for my_list in resolve_func(my_diction):
    print(my_list)

标签: pythonlistdictionary

解决方案


这应该这样做:

my_diction = {5: (50, 'K', 'X'), 6: (60, 'L'), 7: (70, 'M', 'Y', 'Z'), 8: (80, 'N')}

    
def resolve_func(b_dict):
    keys=[]
    values=[]
    for k, tup in b_dict.items(): # iterate over the dictionary. "k" is the key, "tup" are the tuples
        keys.append(k)
        for i, v in enumerate(tup): # iterate over the values "v" in the tuple. With "enumerate" we also get the integer position of the value "i"
            if len(values) <= i: 
                values.append([]) #if sublist doesn't exist yet, create it
            values[i].append(v) #add values to sublist
    return [keys]+values #add the "keys" list to the front of the list of lists

for my_list in resolve_func(my_diction):
    print(my_list)

推荐阅读