简体   繁体   中英

Appending List Items to Dictionary, Python

I have a list with the following items

print(List)
['x, y, z', '1, 2, 3', '2, 4, 6', '4, 8, 12']

and a dictionary containing three empty lists

print(Dictionary)
{0: [], 1: [], 2: []}

Now I want to split each of the items into separate lists

print(List1)
['x', 'y', 'z']

print(List2)
['1', '2', '3']

and so forth..

and then append each item in the new lists to the dictionary so that

print(Dictionary)
{0: ['x', '1', '2', '4'], 1: ['y', '2', '4', '8'], 2: ['z', '3', '6', '12']} 
  1. get list from str in lists . I remove space and split it by , .
  2. I used key of dictionaries as an index of each list.
lists = ['x, y, z', '1, 2, 3', '2, 4, 6', '4, 8, 12']
dictionaries = {0: [], 1: [], 2: []}

lists = [x.replace(' ', '').split(',') for x in lists]
for key in dictionaries.keys():
    dictionaries[key] = [x[key] for x in lists]

print (dictionaries)

The result is:

{0: ['x', '1', '2', '4'], 1: ['y', '2', '4', '8'], 2: ['z', '3', '6', '12']}

With help of itertools :

l = ['x, y, z', '1, 2, 3', '2, 4, 6', '4, 8, 12']
d = {0: [], 1: [], 2: []}

from itertools import chain

for idx, val in zip(sorted(d.keys()), zip(*chain.from_iterable([v.split(', ')] for v in l))):
    d[idx].extend(val)

print(d)

Prints:

{0: ['x', '1', '2', '4'], 1: ['y', '2', '4', '8'], 2: ['z', '3', '6', '12']}

Here's a quick solution

lst = ['x, y, z', '1, 2, 3', '2, 4, 6', '4, 8, 12']
dct = {0: [], 1: [], 2: []}

letters = lst[0].split(', ')

for key in dct:
  numbers = lst[key + 1].split(', ')

  dct[key].append(letters[key])
  dct[key].extend(numbers)

print(dct)

Here is a oneshot way

import re

def dictChunker(content):
    chunker = {}
    for element in content:
        splittedElements = re.findall(r'\w+', element)
        for i in range(len(splittedElements)):
            chunker.setdefault(i, []).append(splittedElements[i])
    return chunker
>>> L = ['x, y, z', '1, 2, 3', '2, 4, 6', '4, 8, 12']
>>> dictChunker(L)
{0: ['x', '1', '2', '4'], 1: ['y', '2', '4', '8'], 2: ['z', '3', '6', '12']}

Here's a one liner using list/dictionary comprehension and zip():

lst= ['x, y, z', '1, 2, 3', '2, 4, 6', '4, 8, 12']

dct = { i:v for i,v in enumerate(zip(*(s.split(", ") for s in lst))) }

# {0: ['x', '1', '2', '4'], 1: ['y', '2', '4', '8'], 2: ['z', '3', '6', '12']}

If you don't mind tuples instead of lists for the dictionary values:

dct = dict(enumerate(zip(*(s.split(", ") for s in lst))))

# {0: ('x', '1', '2', '4'), 1: ('y', '2', '4', '8'), 2: ('z', '3', '6', '12')}

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