How to add values ​​to keys in a dictionary inside a loop?

I have the following list:

x=['a','3','4','b','1','2','c','4','5'] 

How can I make the following dictionary:

 b = {'a':[3,4],'b':[1,2],'c':[4,5]} 

I tried the following:

 Category = defaultdict(int) for i in a: if Varius.is_number(i)==False: Category[i]=[] keys.append(i) else: Category[keys(i)] = i 

Keys are created, but after I had problems inserting values. ( is_number is a function that checks if a list value is a number or a string). First day at MATLAB. First day in Python ..

+5
source share
6 answers

Here is an example that actually uses a function that defaultdict provides over a normal dict :

 from collections import defaultdict x=['a','3','4','b','1','2','c','4','5'] key='<unknown>' # needed if the first value of x is a number category = defaultdict(list) # defaultdict with list for i in x: if i.isalpha(): key = i; else: category[key].append(i) # no need to initialize with an empty list print category 

Also: you must use lowercase names for class instances. Top-level names are usually reserved for classes. Read pep8 for style guide.

+4
source

If the key / value entries in your list x evenly distributed, here is an alternative way to create a dictionary. It uses several built-in Python functions and functions:

 >>> keys = x[::3] >>> values = [map(int, pair) for pair in zip(x[1::3], x[2::3])] >>> dict(zip(keys, values)) {'a': [3, 4], 'b': [1, 2], 'c': [4, 5]} 

To explain what is used here:

  • list slicing to create new lists from x : x[start:stop:step]
  • here zip takes two lists and compiles a list of tuples containing the nth elements of each list
  • map(int, pair) turns a tuple of numbers into a list of integers
  • values is created with a list - the map function is applied to each pair
  • dict turns a list of pairs into dictionary keys / values
+4
source

You can use itertools.groupby :

 >>> from itertools import groupby >>> l=[list(g) for k,g in groupby(x,lambda x : x.isalpha())] >>> p=[l[i:i+2] for i in range(0,len(l),2)] >>> {i[0]:map(int,j) for i,j in p} {'a': [3, 4], 'c': [4, 5], 'b': [1, 2]} 
+2
source

Assuming you have a key in the first positions of your list ( x ), and after the letter there will be a number:

 from collections import defaultdict x=['a','3','4','b','1','2','c','4','5'] key = x[0] Category = defaultdict(int) for i in x: if i.isalpha(): key = i; else: Category[key].append(i) print Category 
+1
source

Using itertools.groupby and some iterators:

 >>> from itertools import groupby >>> it = (next(g) if k else map(int, g) for k, g in groupby(x, str.isalpha)) >>> {k: next(it) for k in it} {'a': [3, 4], 'c': [4, 5], 'b': [1, 2]} 

Here the first iterator will give something like:

 >>> [next(g) if k else map(int, g) for k, g in groupby(x, str.isalpha)] ['a', [3, 4], 'b', [1, 2], 'c', [4, 5]] 

Now, when this iterator will give the key-value alternately, we can iterate over this iterator and get the next element (i.e. value) from it using next()

 >>> it = (next(g) if k else map(int, g) for k, g in groupby(x, str.isalpha)) >>> for k in it: print k,'-->' ,next(it) ... a --> [3, 4] b --> [1, 2] c --> [4, 5] 

There's another way to use this iterator that uses zip , but it's a little hard to understand . IMO:

 >>> it = (next(g) if k else map(int, g) for k, g in groupby(x, str.isalpha)) >>> dict(zip(*[it]*2)) {'a': [3, 4], 'c': [4, 5], 'b': [1, 2]} 
+1
source

A simple solution using only dict and list :

 >>> category = {} >>> for i in x: ... if i.isalpha(): ... items = category[i] = [] ... elif category: ... items.append(i) ... >>> print(category) {'c': ['4', '5'], 'a': ['3', '4'], 'b': ['1', '2']} 
0
source

Source: https://habr.com/ru/post/1208385/


All Articles