Access specific dict value in Python - python

I have a dict object structured in this way:
{'snapshots': [{'snapshot': 'test_2018.11.19', 'uuid': 'Lv1C02wIRYGIljr3S16eIQ', 'version_id': 5060699, 'version': '5.6.6', 'indices': ['cribiscom_x_mydocs_entries_201712'], 'state': 'SUCCESS', 'start_time': '2018-11-19T16:57:44.014Z', 'start_time_in_millis': 1542646664014, 'end_time': '2018-11-19T16:57:46.380Z', 'end_time_in_millis': 1542646666380, 'duration_in_millis': 2366, 'failures': [], 'shards': {'total': 3, 'failed':
0, 'successful': 3}}]}
I would like to get the value of ket state but I'm not really understanding how to do that since 'napshots is a dict and then there is a composed object.
can anyone explain it to me?

This is just a matter of accessing values from a dictionary. You can do it like this:
mydict = {'snapshots': [{'snapshot': 'test_2018.11.19', 'uuid':'Lv1C02wIRYGIljr3S16eIQ', 'version_id': 5060699, 'version': '5.6.6', 'indices': ['cribiscom_x_mydocs_entries_201712'], 'state': 'SUCCESS', 'start_time': '2018-11-19T16:57:44.014Z', 'start_time_in_millis': 1542646664014, 'end_time': '2018-11-19T16:57:46.380Z', 'end_time_in_millis': 1542646666380, 'duration_in_millis': 2366, 'failures': [], 'shards': {'total': 3, 'failed': 0, 'successful': 3}}]}
value = mydict['snapshots'][0]['state']

Related

Dynamic add list in to json-dict as float

Im running a python 3.7 script where im trying to remove quotes.
Im trying to add a dynamic list (x and y coordinates) to a json-dictionary but i keep getting quotes surrounding the list. I need the list to be inserted without these quotes.
Here is my code that im running:
#The dynamic list
polygon = ['0.124912491249125', '0.683368336833683', '0.128112811281128', '0.472147214721472', '-0.096909690969097', '0.444344434443444', '-0.196919691969197', '-0.533353335333533', '-0.64996499649965', '-0.427742774277428', '-0.290529052905291', '-0.266726672667267', '-0.237523752375237', '0.64996499649965']
list_polygon = []
for i,k in zip(polygon[0::2], polygon[1::2]):
data_polygon = ('['+str(i), str(k)+']')
data_polygon = str(data_polygon)
list_polygon.append(data_polygon)
list_polygon = str(list_polygon)
list_polygon = list_polygon.replace("'",'').replace("(",'').replace(")",'').replace("[[",'[').replace("]]",']')
cord_data = {'apiVersion': '1.3',
'context': '<client context>',
'params': {'cameras': [{'active': True, 'id': 1, 'rotation': 0}],
'configurationStatus': 5,
'profiles': [{'camera': 1,
'filters': [{'active': True,
'data': 1,
'type': 'timeShortLivedLimit'},
{'active': True,
'data': 5,
'type': 'distanceSwayingObject'},
{'active': True,
'data': [5, 5],
'type': 'sizePercentage'}],
'name': 'Profile 1',
'triggers': [{'data': [list_polygon],
'type': 'includeArea'}],
'uid': 1}]},
'method': 'setConfiguration'}
And i get the answer:
{'apiVersion': '1.3', 'context': '<client context>', 'params': {'cameras': [{'active': True, 'id': 1, 'rotation': 0}], 'configurationStatus': 5, 'profiles': [{'camera': 1, 'filters': [{'active': True, 'data': 1, 'type': 'timeShortLivedLimit'}, {'active': True, 'data': 5, 'type': 'distanceSwayingObject'}, {'active': True, 'data': [5, 5], 'type': 'sizePercentage'}], 'name': 'Profile 1', 'triggers': [{'data': ['[0.124912491249125, 0.683368336833683], [0.128112811281128, 0.472147214721472], [-0.096909690969097, 0.444344434443444], [-0.196919691969197, -0.533353335333533], [-0.64996499649965, -0.427742774277428], [-0.290529052905291, -0.266726672667267], [-0.237523752375237, 0.64996499649965]'], 'type': 'includeArea'}], 'uid': 1}]}, 'method': 'setConfiguration'}
As you see it adds a quote between the brackets (at the start and the end) 'triggers': [{'data': ['[ 0.124912491249125, 0.683368336833683], [0.128112811281128, 0.472147214721472], [-0.096909690969097, 0.444344434443444], [-0.196919691969197, -0.533353335333533], [-0.64996499649965, -0.427742774277428], [-0.290529052905291, -0.266726672667267], [-0.237523752375237, 0.64996499649965 ]']
Instead i want it to look like this:
'triggers': [{'data': [[ 0.124912491249125, 0.683368336833683], [0.128112811281128, 0.472147214721472], [-0.096909690969097, 0.444344434443444], [-0.196919691969197, -0.533353335333533], [-0.64996499649965, -0.427742774277428], [-0.290529052905291, -0.266726672667267], [-0.237523752375237, 0.64996499649965 ]]
The first and second must be paired.
The post i want to send should look like this:
cord_data = {'apiVersion': '1.3',
'context': '<client context>',
'params': {'cameras': [{'active': True, 'id': 1, 'rotation': 0}],
'configurationStatus': 5,
'profiles': [{'camera': 1,
'filters': [{'active': True,
'data': 1,
'type': 'timeShortLivedLimit'},
{'active': True,
'data': 5,
'type': 'distanceSwayingObject'},
{'active': True,
'data': [5, 5],
'type': 'sizePercentage'}],
'name': 'Profile 1',
'triggers': [{'data': [[0.124912491249125, 0.683368336833683],
[0.128112811281128, 0.472147214721472],
[-0.096909690969097, 0.444344434443444]
and so on],
'type': 'includeArea'}],
'uid': 1}]},
'method': 'setConfiguration'}
What im i doing wrong?
You make every effort to make it str first, when you need list of lists of floats.
polygon = ['0.124912491249125', '0.683368336833683', '0.128112811281128', '0.472147214721472', '-0.096909690969097', '0.444344434443444', '-0.196919691969197', '-0.533353335333533', '-0.64996499649965', '-0.427742774277428', '-0.290529052905291', '-0.266726672667267', '-0.237523752375237', '0.64996499649965']
list_polygon = [[float(i), float(k)] for i,k in zip(polygon[0::2], polygon[1::2])]
cord_data = {'apiVersion': '1.3',
'context': '<client context>',
'params': {'cameras': [{'active': True, 'id': 1, 'rotation': 0}],
'configurationStatus': 5,
'profiles': [{'camera': 1,
'filters': [{'active': True,
'data': 1,
'type': 'timeShortLivedLimit'},
{'active': True,
'data': 5,
'type': 'distanceSwayingObject'},
{'active': True,
'data': [5, 5],
'type': 'sizePercentage'}],
'name': 'Profile 1',
'triggers': [{'data': list_polygon,
'type': 'includeArea'}],
'uid': 1}]},
'method': 'setConfiguration'}
print(cord_data)
And a word of advise - don't forget Floating Point Arithmetic: Issues and Limitations
I guess you'd want something like this:
from pprint import pprint
#The dynamic list
polygon = ['0.124912491249125', '0.683368336833683', '0.128112811281128', '0.472147214721472', '-0.096909690969097', '0.444344434443444', '-0.196919691969197', '-0.533353335333533', '-0.64996499649965', '-0.427742774277428', '-0.290529052905291', '-0.266726672667267', '-0.237523752375237', '0.64996499649965']
list_polygon = []
for i,k in zip(polygon[0::2], polygon[1::2]):
# Don't duplicate convert to `str`, please. Data is already a string.
data_polygon = ([i, k])
# Remove this line, it messes it up if retained
# data_polygon = str(data_polygon)
list_polygon.append(data_polygon)
# Why are we converting all lists to string anyway??
# list_polygon = str(list_polygon)
# list_polygon = list_polygon.replace("'",'').replace("(",'').replace(")",'').replace("[[",'[').replace("]]",']')
# Convert all nested strings to floats
list_polygon = [list(map(float, data_polygon)) for data_polygon in list_polygon]
cord_data = {'apiVersion': '1.3',
'context': '<client context>',
'params': {'cameras': [{'active': True, 'id': 1, 'rotation': 0}],
'configurationStatus': 5,
'profiles': [{'camera': 1,
'filters': [{'active': True,
'data': 1,
'type': 'timeShortLivedLimit'},
{'active': True,
'data': 5,
'type': 'distanceSwayingObject'},
{'active': True,
'data': [5, 5],
'type': 'sizePercentage'}],
'name': 'Profile 1',
# Don't nest it within another list (unless needed)
# 'triggers': [{'data': [list_polygon],
'triggers': [{'data': list_polygon,
'type': 'includeArea'}],
'uid': 1}]},
'method': 'setConfiguration'}
pprint(cord_data)

How to access nested dictionary in python. how do i access total_cases

how do i access the total_cases, death in python
{'data': {'2020-05-28': {'critical': 0,
'death_ratio': 0.0047984644913627635,
'deaths': 5,
'recovered': 187,
'recovery_ratio': 0.17946257197696738,
'tested': 162730,
'total_cases': 1042},
'2020-05-29': {'critical': 1000,
'death_ratio': 0.0049504950495049506,
'deaths': 6,
'recovered': 206,
'recovery_ratio': 0.16996699669966997,
'tested': 0,
'total_cases': 1212}},
'status': 200,
'type': 'stack'}
dictionary_name is the name of your variable.
dictionary_name["data"]["2020-05-29"]["total_cases"]
dictionary_name["data"]["2020-05-29"]["deaths"]
Here's a solution.
[dictionary_name['data'][i]['total_cases'] for i in dictionary_name['data'].keys()]

Why is this weird ID returned when using todoist python api?

This question is regarding the use of todoist python api.
After adding an item (that's what a task is called in the api) I get these weird looking IDs. I say weird because a regular id is just an integer. But these IDs are not usable in anyway, I can't do api.items.get_by_id() with this id. What is going on? How do I get out from this weird state?
'reply email': 'b5b4eb2c-b28f-11e9-bd8d-80e6500af142',
I printed out a few more IDs, and all the integer ones work well with all API calls, the UUID ones throw an exception.
3318771761
3318771783
3318771807
3318771823
3318771843
61c30a10-b2a0-11e9-98d7-80e6500af142
62326586-b2a0-11e9-98d7-80e6500af142
62a3ea9e-b2a0-11e9-98d7-80e6500af142
631222ac-b2a0-11e9-98d7-80e6500af142
63816338-b2a0-11e9-98d7-80e6500af142
63efd14c-b2a0-11e9-98d7-80e6500af142
You have to use api.commit() to do the Sync and have the final id. The id you're trying to use is just a temporary id while the sync is not done.
>>> import todoist; import os; token = os.environ.get('token'); api = todoist.TodoistAPI(token); item=api.items.add('test');
>>> item
Item({'content': 'test',
'id': '3b4d77c0-b891-11e9-a080-2afbabeedbe3',
'project_id': 1490600000})
>>> api.commit()
{'full_sync': False, 'sync_status': {'3b4d793c-b891-11e9-a080-2afbabeaeaef': 'ok'}, 'temp_id_mapping': {'3b4d77c0-b891-11e9-a080-2afbabeaeaef': 3331113774}, 'labels': [], 'project_notes': [], 'filters': [], 'sync_token': 'EEVprctG1E39VDqJfu_cwyhpO6rkOaavyU5r70Eu0nY1ZjsWSjssGr4qLLLikucJAu_Zakld7DniBsEyZ7i820dqcZNcOAbUcbzHFpMpSjzr-GALTA', 'day_orders': {}, 'projects': [], 'collaborators': [], 'day_orders_timestamp': '1564672738.25', 'live_notifications_last_read_id': 2259500000, 'items': [{'legacy_project_id': 1484800000, 'day_order': -1, 'assigned_by_uid': 5050000, 'labels': [], 'sync_id': None, 'section_id': None, 'in_history': 0, 'child_order': 3, 'date_added': '2019-08-06T21:29:18Z', 'id': 3331113774, 'content': 'test2', 'checked': 0, 'user_id': 5050000, 'due': None, 'priority': 1, 'parent_id': None, 'is_deleted': 0, 'responsible_uid': None, 'project_id': 1490600000, 'date_completed': None, 'collapsed': 0}], 'notes': [], 'reminders': [], 'due_exceptions': [], 'live_notifications': [], 'sections': [], 'collaborator_states': []}
>>> item
Item({'assigned_by_uid': 5050000,
'checked': 0,
'child_order': 3,
'collapsed': 0,
'content': 'test',
'date_added': '2019-08-06T21:29:18Z',
'date_completed': None,
'day_order': -1,
'due': None,
'id': 3331100000,
'in_history': 0,
'is_deleted': 0,
'labels': [],
'legacy_project_id': 148400000,
'parent_id': None,
'priority': 1,
'project_id': 1490660000,
'responsible_uid': None,
'section_id': None,
'sync_id': None,
'user_id': 5050000})

How do I turn my JSON into something easier to read?

My Python script connects to an API and gets some JSON.
I've been trying out prettyprint, parse, loads, dumps but I haven't figured them out yet...
Right now, when i do print(request.json()) I get this:
{'info': {'status': 'OK', 'time': {'seconds': 0.050006151199341, 'human': '50 milliseconds'}},
'datalist': {'total': 1, 'count': 1, 'offset': 0, 'limit': 3, 'next': 1, 'hidden': 0, 'loaded': True, 'list': [
{'id': 27862209, 'name': 'Fate/Grand Order', 'package': 'com.xiaomeng.fategrandorder',
'uname': 'komoe-game-fate-go', 'size': 49527668,
'icon': 'http://pool.img.xxxxx.com/msi8/9b58a48638b480c17135a10810374bd6_icon.png',
'graphic': 'http://pool.img.xxxxx.com/msi8/3a240b50ac37a9824b9ac99f1daab8c8_fgraphic_705x345.jpg',
'added': '2017-05-20 10:54:53', 'modified': '2017-05-20 10:54:53', 'updated': '2018-02-12 12:35:51',
'uptype': 'regular', 'store': {'id': 750918, 'name': 'msi8',
'avatar': 'http://pool.img.xxxxx.com/msi8/c61a8cfe9f68bfcfb71ef59b46a8ae5d_ravatar.png',
'appearance': {'theme': 'grey',
'description': '❤️ Welcome To Msi8 Store & My Store Will Mostly Be Specialized in Games With OBB File Extension. I Hope You Find What You Are Looking For Here ❤️'},
'stats': {'apps': 20776, 'subscribers': 96868, 'downloads': 25958359}},
'file': {'vername': '1.14.5', 'vercode': 52, 'md5sum': 'xxxxx', 'filesize': 49527668,
'path': 'http://pool.apk.xxxxx.com/msi8/com-xiaomeng-fategrandorder-52-27862209-32a264b031d6933514970c43dea4191f.apk',
'path_alt': 'http://pool.apk.xxxxx.com/msi8/alt/Y29tLXhpYW9tZW5nLWZhdGVncmFuZG9yZGVyLTUyLTI3ODYyMjA5LTMyYTI2NGIwMzFkNjkzMzUxNDk3MGM0M2RlYTQxOTFm.apk',
'malware': {'rank': 'UNKNOWN'}},
'stats': {'downloads': 432, 'pdownloads': 452, 'rating': {'avg': 0, 'total': 0},
'prating': {'avg': 0, 'total': 0}}, 'has_versions': False, 'obb': None,
'xxxxx': {'advertising': False, 'billing': False}}]}}
But I want it to look like this:
>>> import json
>>> a={"some":"json", "a":{"b":[1,2,3,4]}}
>>> print(json.dumps(a, indent=4, sort_keys=True))
{
"a": {
"b": [
1,
2,
3,
4
]
},
"some": "json"
}

parse data from Dictionary in python

So i have this dictionary "runs":
[{
'id': 12,
'suite_id': 2,
'name': 'name',
'description': "desc.",
'nice_id': 3,
'joku_id': None,
'onko': False,
'eikai': False,
'tehty': None,
'config': None,
'config_ids': [],
'passed_count': 1,
'blocked_count': 2,
'untested_count': 3,
'retest_count': 4,
'failed_count': 5,
'custom_status1_count': 0,
'custom_status2_count': 0,
'custom_status3_count': 0,
'custom_status4_count': 0,
'custom_status5_count': 0,
'custom_status6_count': 0,
'custom_status7_count': 0,
'projekti_id': 1,
'plan_id': None,
'created_on': 12343214,
'created_by': 11,
'url': 'google.com'
}, {
'id': 16,
'suite_id': 2,
'name': 'namae)',
'description': "desc1",
'nice_id': 5,
'joku_id': None,
'onko': False,
'eikai': False,
'tehty': None,
'config': None,
'config_ids': [],
'passed_count': 100,
'blocked_count': 1,
'untested_count': 3,
'retest_count': 2,
'failed_count': 5,
'custom_status1_count': 0,
'custom_status2_count': 0,
'custom_status3_count': 0,
'custom_status4_count': 0,
'custom_status5_count': 0,
'custom_status6_count': 0,
'custom_status7_count': 0,
'prokti_id': 7,
'plan_id': None,
'created_on': 4321341644,
'created_by': 11,
'url': 'google.com/2' }
there is "id" for about 50 times. that is just a part of it.
i need to find all "id":s (Not joku_ids, ncie_ids etc. Only "id") and make a string/dict of them
and same for name, and description
i have tried:
j = json.load(run)
ids = (j["id"])
j = json.load(run)
names = (j["name"])
j = json.load(run)
descriptions = (j["description"])
but it returns:
AttributeError: 'list' object has no attribute 'read'
I also need to send a request with specific id and in this case the specific id is marked by o. so id[o]
the request code is below:
test = client.send_get('get_tests/1/ ')
so i need to have the id[o] instead of the 1.
i have tried
test = client.send_get('get_tests/' + id[o] + '/ ')
but it returns:
TypeError: 'int' object is not subscriptable
May be this can help you.
id = []
for i in runs :
id.append(i.get('id'))
[12, 16]
You are trying to pass a list to a json.load function. Please read the docs. Load() does not accep lists, it accepts
a .read()-supporting file-like object containing a JSON document
If you want your result in list of dictionary then:
result = [{x:y} for i in range(len(data)) for x,y in data[i].items() if x=='id' or x=='name' or x=='description']
output:
[{'name': 'name'}, {'id': 12}, {'description': 'desc.'}, {'name': 'namae)'}, {'id': 16}, {'description': 'desc1'}]
the data is your list of dictionary data.
hope this answer helpful for you.

Categories