python从字符串列表和整数列表创建字典

时间:2016-05-27 05:58:21

标签: python list dictionary

我有两个列表:一个包含['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']等网页的名称,另一个列表包含相应的页码,如[1, 2, 3]

我想从两个列表创建一个字典,以便将列表1中的拆分字作为键,将列表2中的相应值作为值。如果密钥已经在字典中,那么将值附加到它。

对于上面的例子,我想要一个字典,如:

{
 '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                                     
}

3 个答案:

答案 0 :(得分:4)

您可以使用zip()同时循环浏览两个列表。如果你不需要dict,那么使用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)

现在如果你需要dict顺序,你可以使用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,但大多数人会认为这对于这样一个简单的程序来说有点过分。

答案 1 :(得分:0)

你可能会惊讶于结果乱序,但那是因为python中的dicts没有订单。如果你想要它们,你需要使用除香草字典以外的其他东西。

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]}

答案 2 :(得分:0)

列表理解方法。

这里使用列表理解基本上是双重迭代(对我来说看起来更加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)