turn string to array python - python

How can I turn this string
"((145541L, u'/.stats/'), (175706L, u'///')"
to a json object in python such as
{'145541' : '/.stats/',
'175706' : '///'
}
I've been trying tuple() and others but it does
Thanks

Quick fix:
>>> import ast
>>> s = "((145541L, u'/.stats/'), (175706L, u'///')"
>>> {str(k): v for (k, v) in ast.literal_eval(s + ')')}
{'175706': u'///', '145541': u'/.stats/'}
But you should really try looking into json.loads instead.

You do most probably have a tuple of tuples, and want to create a dictionary. To do so, try the following:
data = ((145541L, u'/.stats/'), (175706L, u'///'))
result = dict(data)
If what you have is really a string, add the initial line:
data = "((145541L, u'/.stats/'), (175706L, u'///'))"
data = eval(data)
result = dict(data)
As pointed by #Volatility, eval may be dangerous, since it evaluates any piece of code, not only literals. This way someone could execute commands on your program if you received commands on your strings.
To avoid so, you may use ast.literal_eval instead:
from ast import literal_eval
data = "((145541L, u'/.stats/'), (175706L, u'///'))"
result = dict(literal_eval(data))

Related

Python: split this length-structured string the most elegant way

Given this string:
fsw="M525x617M525x617S16d48492x577S10000505x544S22a00506x524S21300487x601S37601511x574S34500482x483
I'd like to convert
fsw[8:] (thus "M525x617S16d48492x577S10000505x544S22a00506x524S21300487x601S37601511x574S34500482x483")
in a dictionary containing:
{'S16d48':'492x577', 'S10000':'505x544', 'S22a00':'506x524', 'S21300':'487x601', 'S37601':'511x574', 'S34500':'482x483'}
I managed to get the following with regexp:
>>> import re
>>> re.findall("S[123][0-9a-f]{2}[0-5][0-9a-f]",fsw[8:])
['S16d48', 'S10000', 'S22a00', 'S21300', 'S37601', 'S34500']
>>> re.findall("S[123][0-9a-f]{2}[0-5][0-9a-f].......",fsw[8:])
['S16d48492x577', 'S10000505x544', 'S22a00506x524', 'S21300487x601', 'S37601511x574', 'S34500482x483']
but as far as a dictionary is concerned... I failed to get any further.
Another question: in a Python dictionary it is well the whole
key-value pair (say "S16d48":"492x577") that must be unique right ?
In advance - thanks a lot.
Regards.
It seems you can alter your expression to
(?P<key>S[123][0-9a-f]{2}[0-5][0-9a-f])
(?P<value>\d+x\d+)
And then do a dict comprehension as in
import re
rx = re.compile(r'(?P<key>S[123][0-9a-f]{2}[0-5][0-9a-f])(?P<value>\d+x\d+)')
data = "M525x617M525x617S16d48492x577S10000505x544S22a00506x524S21300487x601S37601511x574S34500482x483"
result = {m["key"]: m["value"] for m in rx.finditer(data)}
This yields
{'S16d48': '492x577', 'S10000': '505x544', 'S22a00': '506x524', 'S21300': '487x601', 'S37601': '511x574', 'S34500': '482x483'}
See a demo for the expression on regex101.com and for the code on ideone.com.
You can convert the lists you already created to a dictionary in the following way:
import re
fsw="M525x617M525x617S16d48492x577S10000505x544S22a00506x524S21300487x601S37601511x574S34500482x483"
str_lst = re.findall("S[123][0-9a-f]{2}[0-5][0-9a-f]",fsw[8:])
full_lst = re.findall("S[123][0-9a-f]{2}[0-5][0-9a-f].......",fsw[8:])
str_dict = {x: y[len(x):] for x in str_lst for y in full_lst if y.startswith(x)}
This gives:
{'S16d48': '492x577',
'S10000': '505x544',
'S22a00': '506x524',
'S21300': '487x601',
'S37601': '511x574',
'S34500': '482x483'}
Not sure if I have understood what you are trying to do, but one way to obtain your dictionary from that string is
d = {}
for piece in fsw[8:].split('S')[1:]:
d["S"+piece[:5]] = piece[5:]
print(d)

Parsing a stringified OrderedDictionary in Python

I have a need to change one of my dictionaries from a normal dict to a collections.OrderedDict. The problem is that I store my dictionary as a string in an object that I need to later extract. Call my dict object foo. My previous method of doing this was:
storedDict = str(foo)
Then in another file:
import ast
parsedDict = ast.literal_eval(storedDict)
This works all fine and dandy, but now that I have changed foo to be an OrderedDict, it can no longer be parsed by the ast.literal_eval function. Is there a function or good method I can use to parse a stringified OrderedDict? I am trying to avoid serialization here to stay consistent with the rest of the program.
Seems like the easiest way is to write your own serializer for it; especially because it's an ordered dict, so you want to keep the order, I assume.
It could be as simple as this (assuming your keys and values are simple:
buf = ""
for k, v in myOrderedDict.iteritems():
buf += k + "\t" + v + "\n"
print(buf)
If the data can be more complicated, you can escape or quote as needed.
Then when you want it back:
d = ordereddict()
while(True):
r = readline()
k, v = r.split('\t')
d[k] = v

how to create a dictionary from a set of properly formatted tuples in python

Is there a simple way to create a dictionary from a list of formatted tuples. e.g. if I do something like:
d={"responseStatus":"SUCCESS","sessionId":"01234","userId":2000004904}
This creates a dictionary called d. However, if I want to create a dictionary from a string which contains the same string, I can't do that
res=<some command that returns {"responseStatus":"SUCCESS","sessionId":"01234","userId":2000004904}>
print res
# returns {"responseStatus":"SUCCESS","sessionId":"01234","userId":2000004904}
d=dict(res)
This throws an error that says:
ValueError: dictionary update sequence element #0 has length 1; 2 is required
I strongly strongly suspect that you have json on your hands.
import json
d = json.loads('{"responseStatus":"SUCCESS","sessionId":"01234","userId":2000004904}')
would give you what you want.
Use dict(zip(tuples))
>>> u = ("foo", "bar")
>>> v = ("blah", "zoop")
>>> d = dict(zip(u, v))
>>> d
{'foo': 'blah', 'bar': 'zoop'}
Note, if you have an odd number of tuples this will not work.
Based on what you gave is, res is
# returns {"responseStatus":"SUCCESS","sessionId":"01234","userId":2000004904}
So the plan is to grab the string starting at the curly brace to the end and use json to decode it:
import json
# Discard the text before the curly brace
res = res[res.index('{'):]
# Turn that text into a dictionary
d = json.loads(res)
All you need to do in your particular case is
d = eval(res)
And please keep security in mind when using eval, especially if you're mixing it with ajax/json.
UPDATE
Since others pointed out you might be getting this data over the web and it isn't just a "how to make this work" question, use this:
import json
json.loads(res)

How can I parse a dictionary string?

I am trying to convert a string to a dictionary with dict function, like this
import json
p = "{'id':'12589456'}"
d = dict(p)
print d['id']
But I get the following error
ValueError: dictionary update sequence element #0 has length 1; 2 is required
Why does it fail? How can I fix this?
What you have is a string, but dict function can only iterate over tuples (key-value pairs) to construct a dictionary. See the examples given in the dict's documentation.
In this particular case, you can use ast.literal_eval to convert the string to the corresponding dict object, like this
>>> p = "{'id':'12589456'}"
>>> from ast import literal_eval
>>> d = literal_eval(p)
>>> d['id']
'12589456'
Since p is a string containing JSON (ish), you have to load it first to get back a Python dictionary. Then you can access items within it:
p = '{"id":"12589456"}'
d = json.loads(p)
print d["id"]
However, note that the value in p is not actually JSON; JSON demands (and the Python json module enforces) that strings are quoted with double-quotes, not single quotes. I've updated it in my example here, but depending on where you got your example from, you might have more to do.

which is the best way to get the value of 'session_key','uid','expires'

i have a string
'''
{"session_key":"3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986","uid":164
23386,"expires":12673200,"secret":"sm7WM_rRtjzXeOT_jDoQ__","sig":"6a6aeb66
64a1679bbeed4282154b35"}
'''
how to get the value .
thanks
>>> import json
>>> s=''' {"session_key":"3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986","uid":16423386,"expires":12673200,"secret":"sm7WM_rRtjzXeOT_jDoQ__","sig":"6a6aeb66 64a1679bbeed4282154b35"} '''
>>> d=json.loads(s)
>>> d['session_key']
u'3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986'
>>> d['uid']
16423386
>>> d['expires']
12673200
>>> d['secret']
u'sm7WM_rRtjzXeOT_jDoQ__'
>>> d['sig']
u'6a6aeb66 64a1679bbeed4282154b35'
>>>
The string appears to be JSON.
import json
obj= json.loads( aString )
obj['session_key']
Or it could be a Python dict. Try
obj= eval(myString)
obj['session_key']
For a simple-to-code method, I suggest using ast.parse() or eval() to create a dictionary from your string, and then accessing the fields as usual. The difference between the two functions above is that ast.parse can only evaluate base types, and is therefore more secure if someone can give you a string that could contain "bad" code.

Categories