Sohaib
Sohaib

Reputation: 75

How to append lists in a dictionary in Python?

Hey everyone this code is working fine just one thing to deal with. It overwrites the multiple entries against a key. I need to avoid the overwriting and to save all those entries. Can you help me in this please?

#!/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]

Note: Sys.stdin takes a string in the following format; 1.0.0.0/24|US|158.93.182.221|GB|7018 1221 3359 3412 2543 1873

Upvotes: 2

Views: 1113

Answers (2)

agf
agf

Reputation: 176750

You've got a number of problems with your code. The simplest way to do what you describe is to use a defaultdict, which gets rid of the explicit if and has_key (which you should replace by new in dic anyway):

#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

See eryksun's comment on Gerrat's answer if you're on an old version of Python without defaultdict.

Upvotes: 5

Gerrat
Gerrat

Reputation: 29680

There is no method called appendlist. use append:

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

Also, it's inadvisable to use list as a variable name.
It is a builtin in python.

Also, this entire section of code:

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

should instead probably be:

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

Upvotes: 1

Related Questions