group by a list in dictionary

Viewed 37

I have two lists

list1 = ['good_book.sav',  'master_link', 'there_is_link_there', 'book_name.sav', 'something_else']
list2 = ['book', 'link']

Based on items available in list2, I want to group items of list1 to have a dictionary like,

grouped_dictionary = {'book': ['good_book.sav', 'book_name.sav'],
                      'link': ['master_link', 'there_is_link_there']}

Any help is appreciated.

4 Answers
grouped_dictionary = {key: [word for word in list1 if key in word]
                      for key in list2}

You can solve this using dict.setdefault:

>>> list1 = ['good_book.sav',  'master_link', 'there_is_link_there', 'book_name.sav', 'something_else']
>>> list2 = ['book', 'link']
>>> d = {}
>>> for category in list2:
...   for item in list1:
...     if category in item:
...       d.setdefault(category, []).append(item)
...
>>> d
{'book': ['good_book.sav', 'book_name.sav'], 'link': ['master_link', 'there_is_link_there']}

see below

from collections import defaultdict

list1 = ['good_book.sav', 'master_link', 'there_is_link_there', 'book_name.sav', 'something_else']
list2 = ['book', 'link']

data = defaultdict(list)
for val in list2:
    for name in list1:
        if val in name:
            data[val].append(name)
print(data)

output

defaultdict(<type 'list'>, {'book': ['good_book.sav', 'book_name.sav'], 'link': ['master_link', 'there_is_link_there']})

Try:

list1 = [
    "good_book.sav",
    "master_link",
    "there_is_link_there",
    "book_name.sav",
    "something_else",
]
list2 = ["book", "link"]

grouped_dictionary = {v: [] for v in list2}
for i in list1:
    for k, v in grouped_dictionary.items():
        if k in i:
            v.append(i)

print(grouped_dictionary)

Prints:

{
    "book": ["good_book.sav", "book_name.sav"],
    "link": ["master_link", "there_is_link_there"],
}
Related