views:

151

answers:

2

Hi all,

I have a file with the following structure:

system.action.webMessage=An error has happened during web access. system.action.okMessage=Everything is ok. core.alert.inform=Error number 5512.

I need a script to compare the keys in 2 files with this structure. I was working in a script to convert the file into a dictionary and use the dictionary structure to compare de keys (strings before '=') in both files and tells me with value from which key is equal.

file = open('system.keys','r')
lines = []
for i in file:
    lines.append(i.split('='))

dic = {}
for k, v in lines:
    dic[k] = v

But I'm receiving the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

Any one have some clue or help? :( I've try lots of things that I found in google but no solution.

A: 

If a line has more than one '=' in it, you'll get a list with more than two items, while your for-loop (for k, v in items) expects that each list will only have two items.

Try using i.split('=', 1).

For example:

>>> "a=b=c".split('=')
['a', 'b', 'c']
>>> "a=b=c".split('=', 1)
['a', 'b=c']
David Wolever
I got this error only in the secound 'for', when it trys to convert the list into a dictionary.Both files has only one '=' in each line.
Leonardo
@Leonardo, that is because `lines` has items with more than 2 elements in it
gnibbler
+2  A: 
file = open('system.keys','r')
lines = []
for i in file:
    lines.append(i.partition('='))

dic = {}
for k,_,v in lines:
    dic[k] = v

or using split

myfile = open('system.keys','r')
dic = dict(i.split("=",1) for i in myfile)

since dict() knows how to make a dictionary from a sequence of (key,value) pairs

gnibbler
Thaks man! It works!!! :)
Leonardo