python - 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)
解决方案
这应该这样做:
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)
推荐阅读
- java - 使用比较器按预定义的优先级顺序排序
- javascript - 如何将 d3 树布局从顶部翻转到底部顶部并调整大小以在不同设备上看起来不错
- android - genymotion界面倒置
- java - 我尝试从服务器(python)发送列表长度并发送列表项并由客户端(java)使用套接字 IO 接收它
- django - 不断得到这个:TypeError:元类冲突:派生类的元类必须是其所有基类的元类的(非严格)子类
- c++ - 如何在 C++ 中将指针数组传递给函数模板
- python - 在 Python 中为两个排序列表合并排序算法 - 构造 for 循环的麻烦
- javascript - Webpack:从javascript内部获取块列表
- codenameone - 我错过了 CodenameOne Hellp World 程序中的一些导入
- postgresql - 如果表已经存在于 typeorm 中,是否有必要定义表的实体文件(顺便说一句,如果重要的话,我正在使用 postgres)?