Skip to content

Instantly share code, notes, and snippets.

@JarenGlover
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JarenGlover/a7441771f07469375f30 to your computer and use it in GitHub Desktop.
Save JarenGlover/a7441771f07469375f30 to your computer and use it in GitHub Desktop.
JSON --> Iterable object (List) 2.0
# improvement on how to build a dic from a string
# -> http://www.jarenglover.com/post/106593630960/creating-iterable-objects
# http://stackoverflow.com/questions/988228/converting-a-string-to-dictionary
# this only works if you know it will be valued JSON
>>> import ast
>>> line
'{"domain": {}, "buzz": "", "userid": 0.0, "hours": [20.0, 30.0, 40.0, 20.0, 30.0, 40.0, 35.0, 10.0, 0.0, 15.0, 25.0, 30.0, 10.0, 35.0, 30.0, 30.0, 30.0, 40.0, 25.0, 30.0, 35.0, 15.0, 65.0, 20.0], "buzzid": 0.0, "user": "", "time": 15736, "query": {}, "total": 660.0, "type": 0.0}\n'
>>> type(line)
<type 'str'>
>>> ast.literal_eval(line)
{'domain': {}, 'time': 15736, 'userid': 0.0, 'hours': [20.0, 30.0, 40.0, 20.0, 30.0, 40.0, 35.0, 10.0, 0.0, 15.0, 25.0, 30.0, 10.0, 35.0, 30.0, 30.0, 30.0, 40.0, 25.0, 30.0, 35.0, 15.0, 65.0, 20.0], 'buzzid': 0.0, 'user': '', 'buzz': '', 'query': {}, 'total': 660.0, 'type': 0.0}
>>> dic = ast.literal_eval(line)
>>> type(dic)
<type 'dict'>
>>> print dic
{'domain': {}, 'time': 15736, 'userid': 0.0, 'hours': [20.0, 30.0, 40.0, 20.0, 30.0, 40.0, 35.0, 10.0, 0.0, 15.0, 25.0, 30.0, 10.0, 35.0, 30.0, 30.0, 30.0, 40.0, 25.0, 30.0, 35.0, 15.0, 65.0, 20.0], 'buzzid': 0.0, 'user': '', 'buzz': '', 'query': {}, 'total': 660.0, 'type': 0.0}
>>> dic[hours]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'hours' is not defined
>>> dic['hours']
[20.0, 30.0, 40.0, 20.0, 30.0, 40.0, 35.0, 10.0, 0.0, 15.0, 25.0, 30.0, 10.0, 35.0, 30.0, 30.0, 30.0, 40.0, 25.0, 30.0, 35.0, 15.0, 65.0, 20.0]
>>> dic['hours'][0]
20.0
>>> dic['hours'][15]
30.0
>>> dic['hours'][5:15]
[40.0, 35.0, 10.0, 0.0, 15.0, 25.0, 30.0, 10.0, 35.0, 30.0]
>>> type(dic['hours'][1])
<type 'float'>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment