簡體   English   中英

如何在Python字典中追加列表?

[英]How to append lists in a dictionary in 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

您的代碼有很多問題。 做您描述的最簡單的方法是使用defaultdict ,它擺脫了顯式的ifhas_key (無論如何您都應該用new in dicnew 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

如果您使用的是不帶defaultdict的舊版本Python,請參見eryksun對Gerrat答案的評論。

沒有稱為追加列表的方法。 使用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]] 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM