简体   繁体   中英

Python what is the fastest way to make this list tuples into a dict?

I have a list of tuples that looks like this;

li = [('Replicate 1', '_E748_.txt'),
      ('Replicate 1', '_E749_.txt'),
      ('Replicate 2', '_E758_.txt'),
      ('Replicate 2', '_E759_.txt')]

What is the fastest way to create a dict that looks like this;

{'Replicate1': ['_E748_.txt', '_E749_.txt'],
 'Replicate2': ['_E758_.txt', '_E759_.txt']}

Given

>>> li = [('Replicate 1', '_E748_.txt'),
...       ('Replicate 1', '_E749_.txt'),
...       ('Replicate 2', '_E758_.txt'),
...       ('Replicate 2', '_E759_.txt')]

Do

>>> d = {}
>>> for k, v in li:
...     d.setdefault(k, []).append(v)
...
>>> d
{'Replicate 2': ['_E758_.txt', '_E759_.txt'], 'Replicate 1': ['_E748_.txt', '_E749_.txt']}

Or

>>> from collections import defaultdict
>>> d2 = defaultdict(list)
>>> for k, v in li:
...     d2[k].append(v)
...
>>> d2
defaultdict(<type 'list'>, {'Replicate 2': ['_E758_.txt', '_E759_.txt'], 'Replicate 1': ['_E748_.txt', '_E749_.txt']})

Or even the overly fancy

>>> from itertools import groupby
>>> from operator import itemgetter
>>> get0, get1 = itemgetter(0), itemgetter(1)
>>> dict((key, list(map(get1, subit))) for key, subit in groupby(sorted(li), get0))
{'Replicate 2': ['_E758_.txt', '_E759_.txt'], 'Replicate 1': ['_E748_.txt', '_E749_.txt']}

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