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
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 explicitifandhas_key(which you should replace bynew in dicanyway):See eryksun’s comment on Gerrat’s answer if you’re on an old version of Python without
defaultdict.