Python|将元组值分类到字典值列表中
有时,在使用Python时,我们可能会遇到一个问题,即我们有元组列表形式的数据,我们打算将它们分类到具有元组值列表的字典中。让我们讨论可以执行此任务的某些方式。
方法 #1:使用setdefault()
+ 循环
使用setdefault()
可以轻松执行此任务。在此,我们只是通过迭代获取元组的键值对,并使用setdafault()
将值分配给字典的相应键。
# Python3 code to demonstrate working of
# Categorize tuple values into dictionary value list
# Using setdefault() + loop
# Initialize list of tuples
test_list = [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
# printing original list
print("The original list : " + str(test_list))
# Using setdefault() + loop
# Categorize tuple values into dictionary value list
res = {}
for i, j in test_list:
res.setdefault(j, []).append(i)
# printing result
print("The dictionary converted from tuple list : " + str(res))
输出 :
The original list : [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
The dictionary converted from tuple list : {2: [3], 3: [1, 2, 5], 4: [1, 6]}
方法 #2:使用dict()
+ 列表理解 + frozenset()
上述方法的组合可用于执行此特定任务。在这种情况下,逻辑计算是在frozenset()
的帮助下完成的,并且容器使用dict()
转换为字典。
# Python3 code to demonstrate working of
# Categorize tuple values into dictionary value list
# Using dict() + list comprehension + frozenset()
# Initialize list of tuples
test_list = [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
# printing original list
print("The original list : " + str(test_list))
# Using dict() + list comprehension + frozenset()
# Categorize tuple values into dictionary value list
res = dict((key, [i[0] for i in test_list if i[1] == key])
for key in frozenset(j[1] for j in test_list))
# printing result
print("The dictionary converted from tuple list : " + str(res))
输出 :
The original list : [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
The dictionary converted from tuple list : {2: [3], 3: [1, 2, 5], 4: [1, 6]}