質問

I have a query which give me results like this one by one:

k1=v1
k2=v2
k3=v3
…

The variable to hold the result is tmp. I just wanted to create a dictionary for the results once a result is retrieved. I tried:

result={} 
result.update(tmp)

I got

ValueError: dictionary update sequence element #0 has length 1; 2 is required.

I tried this

result.update(tmp.replace("=",":"))

I got the same err. I don'twant to do substring to get the keys and values then use d(k1)=v1 to build the dict. is there other good way to do it? I also can change the query and let it generate results like k1:v1, k2:v2,... How can I dynamically create a dictionary for this in python 2.4? Thank you!

役に立ちましたか?

解決

If tmp is a string of k1 = v1 pairs, one per line, you'll need to parse those out into pairs:

result = {}
for result in query:
    key, value = result.split('=', 1)
    result[key.strip()] = value.strip()

This presumes your query returns individual 'key1=value1' strings to split out into key and value pairs.

Only use result.update() with a sequence of key-value pairs, or another dictionary. Just passing in a string won't work; Python treats the string as a sequence of one-character strings, and a one-character string does not fit the requirement for a key-value pair.

他のヒント

You have to split the resulting string into lines, and each line into a pair of strings. This gives you a valid input for the dict constructor:

result = dict(line.strip().split("=", 1) for line in tmp.splitlines())

It sounds like you have a query string. If that's the case, then your best friend is urllib.urldecode().

If you actually have a series of newlines, then you'll want to do something a bit more custom.

# splitlines will split based on \r or \n or the combination
pairs = tmp.splitlines()
# initialize a dict
output = {}

for pair in pairs:
    # split the k/v into two parts, the 1 means only break off the first =
    k,v = pair.split('=',1)
    # assign to the output dict. (you may want k.strip and v.strip to clear extra
    # unneeded whitespace.
    output[k] = v

Or, if you're feeling really fancy and want to do it all:

dict(map(lambda x: x.strip(),line.strip().split("=", 1)) for line in tmp.splitlines())

If the results of the query can be stored as a python script into a file results.py, another solution is using execfile:

$ cat results.py
k1="v1"
k2="v2"
$ python
>>> result = {}
>>> execfile("results.py",{},result)
>>> print result
{'k1': 'v1', 'k2': 'v2'}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top