如何在Python中的字典中附加列表?

时间:2011-08-29 21:18:31

标签: python

嘿大家这个代码工作正常只需处理一件事。它会根据密钥覆盖多个条目。我需要避免覆盖并保存所有这些条目。你可以帮帮我吗?

#!/usr/bin/python

import sys
import fileinput

#trys to create dictionary from african country list
dic = {}

for line in sys.stdin:
    lst = line.split('|')
    links = lst[4].split()
    new=links[0] + ' ' + links[len(links)-1]
    dic[new]=lst[4] # WARNING: overwrites multiple entriess at the moment! :)

for newline in fileinput.input('somefile.txt'):
    asn = newline.split()
    new = asn[0] + ' ' + asn[1]
    if new in dic:
            print "found from " + asn[0] + " to " + asn[1]
            print dic[new]

注意:Sys.stdin采用以下格式的字符串; 1.0.0.0/24|US|158.93.182.221|CN | 7018 1221 3359 3412 2543 1873

2 个答案:

答案 0 :(得分:5)

您的代码存在许多问题。执行所描述内容的最简单方法是使用defaultdict,它会删除明确的ifhas_key(无论如何都要用new in dic替换):< / p>

#trys to create dictionary from african country list
from collections import defaultdict

dic = defaultdict(list)   # automatically creates lists to append to in the dict

for line in sys.stdin:
    mylist = line.split('|')    # call it mylist instead of list
    links = mylist[4].split()
    new = links[0] + ' ' + links[-1]   # can just use -1 to reference last item
    dic[new].append(mylist[4])         # append the item to the list in the dict
                                # automatically creates an empty list if needed

如果您使用的是没有defaultdict的旧版Python,请参阅eryksun对Gerrat答案的评论。

答案 1 :(得分:1)

没有名为appendlist的方法。使用append

dic[dic[new]].append(list[4])

此外,不建议使用list作为变量名称 它是内置于python中。

此外,这整段代码:

    if ( dic.has_key(new))
        dic[dic[new]].appendlist(list[4])
    else:
       dic[dic[new]] = [list[4]] 

应该可能是:

    if new in dic:  # this is the preferrable way to test this
        dic[new].append(list[4])
    else:
       dic[new] = [list[4]]