[英]python create dictionary from list of strings and list of integers
我有兩個列表:一個包含頁面名稱,例如['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']
,而另一個列表則包含相應的頁碼,例如[1, 2, 3]
我想從兩個列表中創建一個字典,以便將列表一中的拆分詞作為鍵,並將列表二中的對應值作為值。 如果密鑰已經在字典中,則將值附加到字典中。
對於上面的示例,我想要一個像這樣的字典:
{
'Barrel': [1],
'-': [1],
'Part': [1],
'1': [1],
'Petit': [2],
'Trees': [2],
# '(sketch)': [2],
'Island': [3],
'(sketch)':[2, 3] #in this line the value appended as the key already has a value 2
}
您可以使用zip()
同時遍歷兩個列表。 如果您不需要字典,那么使用collections.defaultdict()
比普通字典要容易得多:
import collections
titles = ['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']
pages = [1, 2, 3]
d = collections.defaultdict(list)
for title, page in zip(titles, pages):
for word in title.split():
d[word].append(page)
盡管由於pages
只是后續編號的列表,所以最好使用enumerate
這樣就不必在每次更改時都更新pages
列表:
import collections
titles = ['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']
d = collections.defaultdict(list)
for page, title in enumerate(titles, start=1):
for word in title.split():
d[word].append(page)
現在,如果您確實需要按順序排列字典,則可以將OrderedDict
與@Keatinge的答案結合使用:
import collections
titles = ['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']
d = collections.OrderedDict()
for title, page in enumerate(titles, start=1):
for word in title.split():
if word not in d:
d[word] = [page]
else:
d[word].append(page)
或者,如果只需要對輸出進行排序,請使用較早的defaultdict
解決方案,並在輸出值時放入sorted()
:
for key in sorted(d.keys()):
print('{0}: {1}'.format(key, d[key]))
最后,您可以使用OrderedDefaultDict
,但是大多數人會認為,對於這樣一個簡單的程序,這有點過頭了。
您可能會對結果不正常感到驚訝,但這是因為python中的字典沒有順序。 如果您要他們訂購,則需要使用除香草字典以外的其他東西。
titles = ['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']
pages = [1, 2, 3]
finalDict = {}
for title, page in zip(titles, pages):
for word in title.split(" "):
if word not in finalDict.keys():
finalDict[word] = [int(page)]
else:
finalDict[word] += [int(page)]
print(finalDict)
輸出:
{'Part': [1], '1': [1], 'Trees': [2], 'Island': [3], 'Barrel': [1], '-': [1], '(sketch)': [2, 3], 'Petit': [2]}
列表理解方法。
基本上,這里使用列表理解中的雙迭代(對我來說,看起來更pythonic)。 迭代的另一種方法是使用itertools.chain
。
from collections import defaultdict
d = defaultdict(list)
page_names = ['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']
pages = [1, 2, 3]
for k, v in [(y, x[1]) for x in zip(page_names, pages) for y in x[0].split(' ')]:
d[k].append(v)
如果順序無關緊要,請轉換具有重復鍵的列表。 然后coolections.defaultdict
將非常有用。 雖然純基本的python方法也可以使用,但它是這樣的:
d = {}
for x in l:
if x.key not in l:
d[x.key] = []
d[x.key].append(x.value)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.