【发布时间】:2022-10-05 06:18:45
【问题描述】:
我正在尝试将元组字典转换为元组列表。但是,我需要根据元组键的第一个值这样做。我已经制定了完成此任务的大部分步骤,但我无法弄清楚该过程的第一步。显然,如果有没有这些步骤的更清洁的方法,这些步骤可以忽略,但这是我迄今为止一直在尝试的过程:
input_dict = {("1", "a"): 1.0, ("1", "b"): 2.0, ("2", "a"): 4.0}
desired_output = [(4, "2", "a"), (3, "1", "a")]
# step 1) merge items, summing values based on first term in tuple key, keeping only one occurence of second term in tuple key
## ? can't figure out how to do this step. Does not matter if option 1 or option 2 is produced
desired_step_1_output_option_1 = {("1", "a"): 3.0, ("2", "a"): 4.0}
desired_step_1_output_option_2 = {("1", "b"): 3.0, ("2", "a"): 4.0}
# step 2) order dictionary by value and convert to list of tuples
output_step_2 = sorted(desired_step_1_output_option_1.items(), key=lambda item: item[1], reverse = True)
## Output: [(('2', 'a'), 4.0), (('1', 'a'), 3.0)]
# step 3) Re-order results
output_step_3 = [(keys, value) for value, keys in output_step_2]
## Output: [(4.0, ('2', 'a')), (3.0, ('1', 'a'))]
# step 4) convert values to int, and un-nest tuples
output_step_4 = [(int(value), *keys) for value, keys in output_step_3]
## Output: [(4, '2', 'a'), (3, '1', 'a')]
【问题讨论】:
标签: python dictionary tuples flatten dictionary-comprehension