Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

List of three tuples to a dictionary from the list of lists

$
0
0

I need the first item in the each tuple to be the key that returns a list of lists of the corresponding items. For example...

This is my input data:

my_problem = [(1,20,400), (1,30,450), (2,40,525), (2,50,600), (2,70,680),(3,80,700), (3,90,980)]

This is what I'm trying to achieve:

my_solution = {'1': [[20,400],[30,450]], '2': [[40,525],[50,600],[70,680]], '3': [[80,700], [90,980]]}

My actual list has thousands of these tuples of varying lengths.

Use a defaultdict . These nice structures are essentially dictionaries that can be initialised with a default value when inserting a key:

from collections import defaultdict solution = defaultdict(list) # create defaultdict with default value [] for item in my_problem: solution[item[0]].append(list(item[1:]))

and to convert back to a dictionary (although this is unncessary, as a defaultdict already has the behaviour of a regular dictionary) you can do

my_solution = dict(solution) A Slightly Neater Formulation in python 3

(kudos to tobias_k for pointing this out)

In Python 3, you can replace the ugly item[0] , etc. calls to use the following: solution = defaultdict(list) for first, *rest in my_problem: solution[first].append(rest)

Viewing all articles
Browse latest Browse all 9596

Trending Articles