Greetings

I'm fairly new to python, and I know that this is possible but I'm having trouble with syntax:

I'm reading a file from the command line and putting it's contents into a dictionary. Keys are repeated in the file, so the values must be placed within a list. In other words, the format for the dictionary must be { Key1 : [Value1, Value2, Value3], Key2 : [ValueX, ValueY], .. etc } rather than { Key1 : Value1, Key1: Value2, Key1: Value3, .. etc}

Both the keys and values are strings. I've tried such operations as

# Line has been split, keyword[1] represents key; keyword[2] represents value

if dict.has_key(keyword[1]):
. . dict[keyword[1]].append(keyword[2])

with little success.

Before inserting the keys and values into the dictionary, I convert the values to a list (containing 1 item). How do I go about appending more objects onto that list once it's placed in the dictionary?

My code segment:

f = open(sys.argv[1])
dict = {}
for line in f:
	keyword = line.split()
	if keyword[0] == 'PUT':  # keyword[1] = key; keyword[2] = value
		if dict.has_key(keyword[1]):
			# append keyword[2] to keyword[1]'s value list
		else:
			templist = keyword[2]
			list(templist)
			dict[keyword[1]] = templist

The following works fine on my machine. Perhaps you should submit some of the data in the file as it may be corrupted. Also, has_key is being replaced with "in".

f = ["PUT key1 value1A", \
     "Junk key1 value1", \
     "PUT key1 value1B", \
     "PUT key2 value2", \
     "PUT key1 value1C" ]

##   don't use dict or list, they are reserved words
##dict = {}
key_dic = {}
for line in f:
     print line
     keyword = line.split()
     if keyword[0] == 'PUT':  # keyword[1] = key; keyword[2] = value
          if keyword[1] in key_dic:
               # append keyword[2] to keyword[1]'s value list
               key_dic[keyword[1]].append(keyword[2])
          else:
               key_dic[keyword[1]] = [keyword[2]]
print key_dic
##
##
##   or you can replace this part of your code
	else:
			templist = keyword[2]
			list(templist)
			dict[keyword[1]] = templist
##
##  with  (also using a name other than "dict")
          else:
               templist = []
               templist.append(keyword[2])
               dict[keyword[1]] = templist
##
##   this will also work
          else:
               templist = list(keyword[2])
               ##  you don't do anything with the list object returned
               ##  list(templist)   ## so this is still a string
               dict[keyword[1]] = templist

A typical application of what you want to achieve is this book page indexing program:

# create a page index using a word:pagenumber dictionary

def do_index(keyword, pagenumber, page_index):
    """
    if keyword exists add pagenumber to that particular list
    otherwise make new entry to index dictionary
    """
    page_index.setdefault(keyword, []).append(pagenumber)
    return page_index


page_index = {}
page_index = do_index('jump', 27, page_index)
page_index = do_index('girl', 45, page_index)
page_index = do_index('boy',99, page_index)
# appends 58 to pagenumber list at word 'jump'
page_index = do_index('jump', 58, page_index)   

print(page_index)

print('-'*50)

# print pagenumber(s) for one keyword
print(page_index['jump'])

print('-'*50)

# remove a pagenumber
page_index['jump'].remove(27)
print(page_index['jump'])

"""
my result -->
{'jump': [27, 58], 'boy': [99], 'girl': [45]}
--------------------------------------------------
[27, 58]
--------------------------------------------------
[58]
"""
dictfeature = {}
for word in line:
        if key in dictfeature:
            dictfeature[key].append(word)
        else:
            listfeature = []
            listfeature.append(word)
            dictfeature[key] = listfeature

You can do everything after the else on one line

        else:
            dictfeature[key] = [word]

Or even better IMHO

        if key not in dictfeature:
            dictfeature[key]=[]
        dictfeature[key].append(word)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.