按字典中的列表分组



我有两个列表

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

基于list2中可用的项,我想将list1中的项分组为一个字典,如

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

任何帮助都是感激的。

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

您可以使用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']}

见下文

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)

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

尝试:

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)

打印:

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

相关内容

  • 没有找到相关文章

最新更新