简体   繁体   中英

Python: transform list of tuples in dictionary

Wondering if there is a more idiomatic (pythonic) way of doing this. I have a list of tuples returned by a cursor object, and I'm trying to regroup the data in a dictionary. The data I get is formatted as such:

[("Département d'informatique", 119, 74, 193),
 ("Département d'informatique", 193, 67, 260), 
 ("Département de chimie", 355, 44, 399) ... ]

Notice that departments repeat. Each line with the same department represents a different kind of data. I need to regroup that data in a dictionary that contains a key (department name) and the value would be a list of all the tuples that have that department as its first member. So something like this:

{ "Département d'informatique": [(119, 74, 193), (193,67,260) ...] }

Here is my code. It's working at the moment but I'm not sure if it's the most efficient/pythonic way of doing things.

def preparer_donnees(data):
    ret = { ligne[0] : [] for ligne in data }

    for ligne in data:
        for entree in ligne[1:]:
            ret[ligne[0]].append(entree)

    return ret

Thanks!

I would use a collections.defaultdict :

def preparer_donnees(data):
    from collections import defaultdict

    ret = defaultdict(list)

    for v in data:
        ret[v[0]].append(v[1:])

    return ret

您可以使用嵌套列表理解:

{line[0] : [tup[1:] for tup in data if tup[0] == line[0]] for line in data}

If all the tuples have 4 elements, you could just unpack the tuples:

my_d = {}

for k, v1, v2, v3 in l:
    if my_d.get(k):
        my_d[k] += [(v1,v2,v3)]
    else:
        my_d[k] = [(v1,v2, v3)]

You can use the dictionary "setdefault" method ( which can be replaced in many cases by using the defaultdict - but not always - I like the setdefault as its more general and quite powerful )

Use cases for the 'setdefault' dict method

def process( data ):
    result = {}
    for vals in data:
        result.setdefault( vals[0], [] ).append( vals[1:] )
    return result

Also, mathsaey's answer

{line[0] : [tup[1:] for tup in data if tup[0] == line[0]] for line in data}

is wrong as the values of his dictionary are list of lists rather than list of values. I don't have enough reputation to comment (new account), so adding this observation here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM