R. Hast
R. Hast

Reputation: 1

How to categorise a list by elements in Python

Say I have a list:

['1,2,3', '1,2,3', '1,3,2', '2,1,3', '2,3,1']

How can I categorise the items into specific keys of a dictionary according to where a specific number is in an item? If 1 is the first number, the item should be added to the value of the first key, if it's the second, it should be added to the value of the second etc.

So if I have a dictionary with keys A, B, C:

{'A': [], 'B': [], 'C': []}

The resulting dictionary should look like:

{'A': ['1,2,3', '1,2,3', '1,3,2'], 'B': ['2,1,3'], 'C':['2,3,1']

At the moment I have the following code:

lst = ['1,2,3', '1,2,3', '1,3,2', '2,1,3', '2,3,1']
dict = {'A': [], 'B': [], 'C': []}
for item in list
    item.strip(',')
    if item[0] == 1:
       dict['A'].append(item)
    elif item[1] == 1:
       dict['B'].append(item)
    elif item[2] == 1:
       dict['C'].append(item)
print(dict)

However, this just returns the original dictionary.

Upvotes: 0

Views: 1124

Answers (3)

Julien Spronck
Julien Spronck

Reputation: 15433

It's less efficient and not very readable but here is a one-liner using dictionary and list comprehensions:

lst = ['1,2,3', '1,2,3', '1,3,2', '2,1,3', '2,3,1']
keys = ['A', 'B', 'C']
dic = {key: [x for x in lst if x.split(',')[j] == '1'] for j, key in enumerate(keys)}
# {'A': ['1,2,3', '1,2,3', '1,3,2'], 'B': ['2,1,3'], 'C': ['2,3,1']}

Upvotes: 0

user_
user_

Reputation: 104

I think you meant to use item.split(',') instead of item.strip(',') which only removes any commas at the start and end of the string item. item.split(',') splits the string item into a list using a comma as the delimiter. Also, you need to save the result of the method call, none of the aforementioned method calls modifies the string.

What you probably want to do is something like:

lst = ['1,2,3', '1,2,3', '1,3,2', '2,1,3', '2,3,1']
dict = {'A': [], 'B': [], 'C': []}

for item in lst:
    item_arr = item.split(',')
    key = 'ABC'[item_arr.index('1')]
    dict[key].append(item)

print(dict)

Upvotes: 0

sp________
sp________

Reputation: 2645

try this:

lst = ['1,2,3', '1,2,3', '1,3,2', '2,1,3', '2,3,1']
dict = {'A': [], 'B': [], 'C': []}
for item in lst:
   l = item.replace(',', '')
   if l[0] == '1':
      dict['A'].append(item)
   elif l[1] == '1':
      dict['B'].append(item)
   elif l[2] == '1':
      dict['C'].append(item)
print(dict)

I hope this helps !

Upvotes: 1

Related Questions