Is there any way to change dictonary items comparing with another one? - python

import json
from urllib import request
infile = request.urlopen('https://restcountries.eu/rest/v1/all')
content_as_python_obj = json.loads(infile.read().decode())
name=[]
boarder=[]
code=[]
for country in content_as_python_obj:
name.append(country['name'])
boarder.append(country['borders'])
code.append(country['alpha3Code'])
countryAndCode=dict(zip(name, code))
countryAndBoarders=dict(zip(name, boarder))
#I would like to replace the codes with the full name to have a dictionary that states the name and the bordering countries with the full name

use the mapping of country code to country name to convert all the country code present in the borders list.
country_code_to_country_name = dict(zip(code, name))
country_borders = dict(zip(name, boarder))
country_borders = {
key: [country_code_to_country_name[v] for v in value]
for key, value in country_borders.items()
}

Related

I want to extract menu_header from bubble_list and then need to extract all titles from menu_list with condition type='menu' only

I want to extract menu_header from bubble_list and then need to extract all titles from menu_list with condition type='menu' only
response3 = [{"thumbs_id":56071,"disable_text":"yes","thumbs_display":"no","recipient_id":"12698","bubble_list":[{"class":"bubble-top","delay":0,"logo":"no","text":"You may only add\/change your preferred first name and legal last name in PIMS.","type":"text"},{"class":"bubble-menu","delay":3000,"logo":"yes","menu_header":"Which name would you like to update?","menu_list":[{"payload":"\/update_name{\"name_type\":\"preferred_first_name\"}","title":"Update Preferred First Name"},{"payload":"\/update_name{\"name_type\": \"legal_last_name\"}","title":"Update Legal Last Name"}],"menu_status":"always_active","type":"menu"}],"button_list":[{"payload":"\/inactivity_timeout","title":"End Chat"},{"payload":"\/bot_help{\"bot_help_value\":\"start_over\"}","title":"Start Fresh again"}],"related_question":[]}]
A bit long but it works:
response = {key:value for key, value in response3[0].items() if key == 'bubble_list'}
filter = [my_dict for my_dict in response['bubble_list'] if 'menu_header' in list(my_dict.keys()) and my_dict.get('type') == 'menu']
menu_header = filter[0]['menu_header']
menu_list = [title.get('title') for title in filter[0]['menu_list']]

How to print specific value from specific key from JSON in Python

I wrote 2 functions so I can get champion ID knowing champion Name but then I wanted to get champion Name knowing champion ID but I cannot figure it out how to extract the name because of how the data structured.
"data":{"Aatrox":{"version":"8.23.1","id":"Aatrox","key":"266","name":"Aatrox"
so in my code I wrote ['data']['championName'(in this case Aatrox)]['key'] to get the champion ID/key. But how can I reverse it if for example I don't know the champion Name but champions ID. How can I get the champion Name if after writing ['data'] I need to write champion Name so I can go deeper and get all the champions info like ID, title etc..
link: http://ddragon.leagueoflegends.com/cdn/8.23.1/data/en_US/champion.json
Code:
def requestChampionData(championName):
name = championName.lower()
name = name.title()
URL = "http://ddragon.leagueoflegends.com/cdn/8.23.1/data/en_US/champion/" + name + ".json"
response = requests.get(URL)
return response.json()
def championID(championName):
championData = requestChampionData(championName)
championID = str(championData['data'][championName]['key'])
return championID
since python values are passed by reference you can make a new dict with keys as the champion id pointing to the values of the previous dict, that way you dont duplicate too much data. but be carefull if you change data in one dict the data will be changed in the other one too
def new_dict(d):
return { val["id"]:val for val in d.values() }
I solved my problem with this code:
def championNameByID(id):
championData = requestChampionData()
allChampions = championData['data']
for champion in allChampions:
if id == allChampions[champion]['key']:
championName = allChampions[champion]['name']
return championName

save two list in one json file

I'm getting data with two lists and I want to save both of them in one single json file can someone help me.
I'm using selenium
def get_name(self):
name = []
name = self.find_elements_by_class_name ('item-desc')
price = []
price = self.find_elements_by_class_name ('item-goodPrice')
for names in name :
names = (names.text)
#print names
for prices in price :
prices = (prices.text)
#print price
I would create a dictionary and then JSON dumps
An example could be:
import json
def get_name(self):
names = [ name.text for name in self.find_elements_by_class_name('item-desc') ]
prices = [ price.text for price in self.find_elements_by_class_name('item-goodPrice')]
with open('output-file-name.json', 'w') as f:
f.write(json.dumps({'names': names, 'prices': prices}))
EDIT: In the first version of the answer I was only creating the JSON, if you want to create a file as well, you should include what suggested by #Andersson comment

How do I look get an associated value in a json variable using python?

How do I look up the 'id' associated with the a person's 'name' when the 2 are in a dictionary?
user = 'PersonA'
id = ? #How do I retrieve the 'id' from the user_stream json variable?
json, stored in a variable named "user_stream"
[
{
'name': 'PersonA',
'id': '135963'
},
{
'name': 'PersonB',
'id': '152265'
},
]
You'll have to decode the JSON structure and loop through all the dictionaries until you find a match:
for person in json.loads(user_stream):
if person['name'] == user:
id = person['id']
break
else:
# The else branch is only ever reached if no match was found
raise ValueError('No such person')
If you need to make multiple lookups, you probably want to transform this structure to a dict to ease lookups:
name_to_id = {p['name']: p['id'] for p in json.loads(user_stream)}
then look up the id directly:
id = name_to_id.get(name) # if name is not found, id will be None
The above example assumes that names are unique, if they are not, use:
from collections import defaultdict
name_to_id = defaultdict(list)
for person in json.loads(user_stream):
name_to_id[person['name']).append(person['id'])
# lookup
ids = name_to_id.get(name, []) # list of ids, defaults to empty
This is as always a trade-off, you trade memory for speed.
Martijn Pieters's solution is correct, but if you intend to make many such look-ups it's better to load the json and iterate over it just once, and not for every look-up.
name_id = {}
for person in json.loads(user_stream):
name = person['name']
id = person['id']
name_id[name] = id
user = 'PersonA'
print name_id[user]
persons = json.loads(...)
results = filter(lambda p:p['name'] == 'avi',persons)
if results:
id = results[0]["id"]
results can be more than 1 of course..

Filtering through a Django Countries list

I'm trying to retrieve a list of tags that share the same name as a django Country. (i will be throwing it into my autocomplete search). What I have isn't working:
View:
from django_countries.countries import COUNTRIES
...
#login_required
def country_tags(request):
result = {}
tags = Tags.objects.all()
countries = list(COUNTRIES)
for tag in tags:
for country in countries:
if country.name == tag.name:
result[tag.name] = tag.name.title()
return HttpResponse(json.dumps(result))
Can't quite figure out why this isn't working. Am I wrong to reference country.name?
Here is a version that should work. COUNTRIES is a 2-tuple tuple.
countries_only = [x[1] for x in COUNTRIES]
tags = Tag.objects.filter(tag.name__in=countries_only)
results = {}
for t in tags:
results[t.name] = t.name.title()
COUNTRIES is just a list of 2 elements tuples - there is no name property. You should do something like country[1] == tag.name.

Categories

Resources