carsentdum
carsentdum

Reputation: 67

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']} 

Upvotes: 0

Views: 182

Answers (5)

Alain T.
Alain T.

Reputation: 42143

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')}

Upvotes: 0

Shizzen83
Shizzen83

Reputation: 3529

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']}

Upvotes: 0

Shane Richards
Shane Richards

Reputation: 341

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)

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195438

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']}

Upvotes: 1

yaho cho
yaho cho

Reputation: 1779

  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']}

Upvotes: 0

Related Questions