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

问题描述:

嘿大家这个代码工作正常只是一件事来处理。它会根据密钥覆盖多个条目。我需要避免覆盖并保存所有这些条目。你能帮我吗?如何在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|GB|7018 1221 3359 3412 2543 1873

+2

你不应该使用'list'作为变量名称,因为它会影响内建函数list()'。另外,你在'if'语句中错过了一个冒号,它应该看起来像这样:'if new in dic:'。至少,这是[pythonic方式](http://www.python.org/dev/peps/pep-0008)。 – pillmuncher

+0

你期望'dic [dic [新]]要做什么,为什么? (提示:'dic [new]'做了什么?) –

你有一些与你的代码的问题。做你的描述最简单的方法是使用defaultdict,它摆脱了明确ifhas_key的(你应该通过new in dic无论如何代替):

#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 
上Gerrat的答案,如果你是

见eryksun的评论在没有defaultdict的Python旧版本中。

+0

谢谢,你建议的改变realy工作。 – Sohaib

没有方法叫做appendlist。使用append

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

此外,这是不可取的使用list作为变量名。
这是一个内置的蟒蛇。

而且,代码本部分内容:

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]] 
+0

嗨,我刚纠正了我所犯的错误。但仍然代码:dic [dic [新]] = [列表[4]]不起作用,并给出错误“'类型'主题是不可上标的”。 – Sohaib

+0

@Sohaib - 作为@Gerrat和我在我们的答案中说过,'dic [dic [new]]'是错误的,但是,它不应该尝试给'type'对象(不是“subject”!错误。你必须意外地键入了'dict'而不是'dic',因为'dict'是一个类型对象,'dic'不是。 – agf

+0

@Gerrat:我试过你的首选方法来测试它,并遇到错误“'str'对象没有属性'append'”。实际上,我试图创建一个包含多个值的字典,每个值都是一个字符串。然后,我会阅读一个新文件的内容,并比较字典中的键,我将在键中打印这些值。 – Sohaib