How to transform an array to json object in python - python

I would like to tranform an array to on object .
I have an array : ['BROOKLYN','STATEN ISLAND','OZONE PARK','SOUTH OZONE PARK', 'JAMAICA','OZONE PARK']
I am going to transofrm it to json object adding ":red" prefix .
colormap = {'NEW YORK': 'red', 'BROOKLYN': 'red', 'STATEN ISLAND': 'red', 'OZONE PARK':'red','SOUTH OZONE PARK':'red', 'JAMAICA':'red','OZONE PARK': 'red'}
How can I do that ?

As I understand, you want to create a dict from your list. If so, you can do it like this:
colormap = {x:'red' for x in myList}
Afterwards, you can save it in json format using json module (please see a relevant question Storing Python dictionaries and documentation).

You can use fromkeys method in the dictionary, like this
print {}.fromkeys(myArray, "set")
Or you can use zip like this
print dict(zip(myArray, ["set"] * len(myArray)))
Output
{'OZONE PARK': 'set', 'BROOKLYN': 'set', 'STATEN ISLAND': 'set', 'SOUTH OZONE PARK': 'set', 'JAMAICA': 'set'}

import json
array = ["test", "test1", "test2"]
colors = {item: "red" for item in array}
json_str_colors = json.dumps(colors)
print(repr(json_str_colors))

Related

How to Loop over dictionary and return output of specific values to Numpy Array

I am trying to loop over a dictionary, in this case the citi bike data, and pull out the values of the specific keys 'lat' and 'lon', and then put those values in a numpy array. I was able to pull the data from the URL but when trying a for loop I am getting stuck. The dictionary is 'datadict' which I pulled from the URL.
import requests
response = requests.get("https://gbfs.citibikenyc.com/gbfs/en/station_information.json")
datadict = response.json()
I tried this comprehension first and then tried forming a regular for statement.
import numpy as np
dict_reduce = {key: datadict[key] for key in datadict.values() & {'lon', 'lat'}}
coordinates = np.array(dict_reduce)
result = list()
for key in datadict:
for x in datadict[key]:
result.append(x['lon'])
Dictionary Preview:
"""
[{'capacity': 55,
'eightd_has_key_dispenser': False,
'eightd_station_services': [],
'electric_bike_surcharge_waiver': False,
'external_id': '66db237e-0aca-11e7-82f6-3863bb44ef7c',
'has_kiosk': True,
**'lat': 40.76727216,**
'legacy_id': '72',
**'lon': -73.99392888,**
'name': 'W 52 St & 11 Ave',
'region_id': '71',
'rental_methods': ['KEY', 'CREDITCARD'],
'rental_uris': {'android': 'https://bkn.lft.to/lastmile_qr_scan',
'ios': 'https://bkn.lft.to/lastmile_qr_scan'},
'short_name': '6926.01',
'station_id': '72',
'station_type': 'classic'},
{'capacity': 33,
'eightd_has_key_dispenser': False,
'eightd_station_services': [],
'electric_bike_surcharge_waiver': False,
'external_id': '66db269c-0aca-11e7-82f6-3863bb44ef7c',
'has_kiosk': True,
'lat': 40.71911552,
'legacy_id': '79',
'lon': -74.00666661,
'name': 'Franklin St & W Broadway',
'region_id': '71',
'rental_methods': ['KEY', 'CREDITCARD'],
'rental_uris': {'android': 'https://bkn.lft.to/lastmile_qr_scan',
'ios': 'https://bkn.lft.to/lastmile_qr_scan'},
'short_name': '5430.08',
'station_id': '79',
'station_type': 'classic'},
"""
Looks like you need.
dict_reduce = [{key: d[key] for key in {'lon', 'lat'} } for d in datadict]
You should be able to directly pull out the lat and long values from each element in the list.
From your dictionary preview it looks more like a list of dictionaries rather than a single dictionary and you need to account for that.
lat_list = list()
long_list = list()
for elem in datadict:
lat_list.append(elem['lat'])
long_list.append(elem['lon'])

Python Print Function City name

I'm trying to print 'Phoenix' from this list dictionary but can't extract the specific name.
test = [{'Arizona': 'Phoenix', 'California': 'Sacramento', 'Hawaii': 'Honolulu'}, 1000, 2000, 3000, ['hat', 't-shirt', 'jeans', {'socks1': 'red', 'socks2': 'blue'}]]
print(test[0]) gives me all the city names... How do I display just 'Phoenix'?
With test[0] you're just accessing the first element of the list test, which in this case is the dictionary.
You need to use the key - in this case Arizona:
print(test[0]['Arizona'])
Output is Phoenix.
You should read up a bit on the dictionary data structure. But here you go:
test[0]['Arizona']
Try to run the below code snippet and you will get your answer by your own most probably.
test = [{'Arizona': 'Phoenix', 'California': 'Sacramento', 'Hawaii': 'Honolulu'}, 1000, 2000, 3000,
['hat', 't-shirt', 'jeans', {'socks1': 'red', 'socks2': 'blue'}]]
print(test[0]['Arizona'])
for index in range(len(test)):
print("test[" + str(index) + "]:")
print(str(test[index]))
print()
The output will be like the below:
Phoenix
test[0]:
{'Arizona': 'Phoenix', 'California': 'Sacramento', 'Hawaii': 'Honolulu'}
test[1]:
1000
test[2]:
2000
test[3]:
3000
test[4]:
['hat', 't-shirt', 'jeans', {'socks1': 'red', 'socks2': 'blue'}]
The output explains that test is an array of 5 elements and the 0th element is an associative array. Thus, to output Phoenix, you have to use test[0]['Arizona']
If you use just test[0], you can just access the first element in the test list:
{'Arizona': 'Phoenix', 'California': 'Sacramento', 'Hawaii': 'Honolulu'}.
The test[0] is a dictionary. And you need to get 'Phoenix' which is the value of the key 'Arizona', you can just use the key to get the value:
test[0]['Arizona']

Filtering through a list with embedded dictionaries

I've got a json format list with some dictionaries within each list, it looks like the following:
[{"id":13, "name":"Albert", "venue":{"id":123, "town":"Birmingham"}, "month":"February"},
{"id":17, "name":"Alfred", "venue":{"id":456, "town":"London"}, "month":"February"},
{"id":20, "name":"David", "venue":{"id":14, "town":"Southampton"}, "month":"June"},
{"id":17, "name":"Mary", "venue":{"id":56, "town":"London"}, "month":"December"}]
The amount of entries within the list can be up to 100. I plan to present the 'name' for each entry, one result at a time, for those that have London as a town. The rest are of no use to me. I'm a beginner at python so I would appreciate a suggestion in how to go about this efficiently. I initially thought it would be best to remove all entries that don't have London and then I can go through them one by one.
I also wondered if it might be quicker to not filter but to cycle through the entire json and select the names of entries that have the town as London.
You can use filter:
data = [{"id":13, "name":"Albert", "venue":{"id":123, "town":"Birmingham"}, "month":"February"},
{"id":17, "name":"Alfred", "venue":{"id":456, "town":"London"}, "month":"February"},
{"id":20, "name":"David", "venue":{"id":14, "town":"Southampton"}, "month":"June"},
{"id":17, "name":"Mary", "venue":{"id":56, "town":"London"}, "month":"December"}]
london_dicts = filter(lambda d: d['venue']['town'] == 'London', data)
for d in london_dicts:
print(d)
This is as efficient as it can get because:
The loop is written in C (in case of CPython)
filter returns an iterator (in Python 3), which means that the results are loaded to memory one by one as required
One way is to use list comprehension:
>>> data = [{"id":13, "name":"Albert", "venue":{"id":123, "town":"Birmingham"}, "month":"February"},
{"id":17, "name":"Alfred", "venue":{"id":456, "town":"London"}, "month":"February"},
{"id":20, "name":"David", "venue":{"id":14, "town":"Southampton"}, "month":"June"},
{"id":17, "name":"Mary", "venue":{"id":56, "town":"London"}, "month":"December"}]
>>> [d for d in data if d['venue']['town'] == 'London']
[{'id': 17,
'name': 'Alfred',
'venue': {'id': 456, 'town': 'London'},
'month': 'February'},
{'id': 17,
'name': 'Mary',
'venue': {'id': 56, 'town': 'London'},
'month': 'December'}]

Find value of dictionary inside a dictionary

I have some data like this:
{'cities': [{'abbrev': 'NY', 'name': 'New York'}, {'abbrev': 'BO', 'name': 'Boston'}]}
From my scarce knowledge of Python this looks like a dictionary within a dictionary.
But either way how can I use "NY" as a key to fetch the value "New York"?
It's a dictionary with one key-value pair. The value is a list of dictionaries.
d = {'cities': [{'abbrev': 'NY', 'name': 'New York'}, {'abbrev': 'BO', 'name': 'Boston'}]}
To find the name for an abbreviation you should iterate over the dictionaries in the list and then compare the abbrev-value for a match:
for city in d['cities']: # iterate over the inner list
if city['abbrev'] == 'NY': # check for a match
print(city['name']) # print the matching "name"
Instead of the print you can also save the dictionary containing the abbreviation, or return it.
When you've got a dataset not adapted to your need, instead of using it "as-is", you can build another dictionary from that one, using a dictionary comprehension with key/values as values of your sub-dictionaries, using the fixed keys.
d = {'cities': [{'abbrev': 'NY', 'name': 'New York'}, {'abbrev': 'BO', 'name': 'Boston'}]}
newd = {sd["abbrev"]:sd["name"] for sd in d['cities']}
print(newd)
results in:
{'NY': 'New York', 'BO': 'Boston'}
and of course: print(newd['NY']) yields New York
Once the dictionary is built, you can reuse it as many times as you need with great lookup speed. Build other specialized dictionaries from the original dataset whenever needed.
Use next and filter the sub dictionaries based upon the 'abbrev' key:
d = {'cities': [{'abbrev': 'NY', 'name': 'New York'},
{'abbrev': 'BO', 'name': 'Boston'}]}
city_name = next(city['name'] for city in d['cities']
if city['abbrev'] == 'NY')
print city_name
Output:
New York
I think that I understand your problem.
'NY' is a value, not a key.
Maybe you need something like {'cities':{'NY':'New York','BO':'Boston'}, so you could type: myvar['cities']['NY'] and it will return 'New York'.
If you have to use x = {'cities': [{'abbrev': 'NY', 'name': 'New York'}, {'abbrev': 'BO', 'name': 'Boston'}]} you could create a function:
def search(abbrev):
for cities in x['cities']:
if cities['abbrev'] == abbrev:
return cities['name']
Output:
>>> search('NY')
'New York'
>>> search('BO')
'Boston'
PD: I use python 3.6
Also with this code you could also find abbrev:
def search(s, abbrev):
for cities in x['cities']:
if cities['abbrev'] == abbrev: return cities['name'], cities['abbrev']
if cities['name'] == abbrev: return cities['name'], cities['abbrev']

Use list of indices to manipulate a nested dictionary

I'm trying to perform operations on a nested dictionary (data retrieved from a yaml file):
data = {'services': {'web': {'name': 'x'}}, 'networks': {'prod': 'value'}}
I'm trying to modify the above using the inputs like:
{'services.web.name': 'new'}
I converted the above to a list of indices ['services', 'web', 'name']. But I'm not able to/not sure how to perform the below operation in a loop:
data['services']['web']['name'] = new
That way I can modify dict the data. There are other values I plan to change in the above dictionary (it is extensive one) so I need a solution that works in cases where I have to change, EG:
data['services2']['web2']['networks']['local'].
Is there a easy way to do this? Any help is appreciated.
You may iterate over the keys while moving a reference:
data = {'networks': {'prod': 'value'}, 'services': {'web': {'name': 'x'}}}
modification = {'services.web.name': 'new'}
for key, value in modification.items():
keyparts = key.split('.')
to_modify = data
for keypart in keyparts[:-1]:
to_modify = to_modify[keypart]
to_modify[keyparts[-1]] = value
print(data)
Giving:
{'networks': {'prod': 'value'}, 'services': {'web': {'name': 'new'}}}

Categories

Resources