I have below List:
dimensionList = [{'key': 2109290, 'id': 'R', 'name': 'Reporter', 'isGeo': True, 'geoType': 'region'},
{'key': 2109300, 'id': 'C', 'name': 'Commodity', 'isGeo': False, 'geoType': None},
{'key': 2109310, 'id': 'P', 'name': 'Partner', 'isGeo': True, 'geoType': 'region'},
{'key': 2109320, 'id': 'TF', 'name': 'Trade Flow', 'isGeo': False, 'geoType': None},
{'key': 2109330, 'id': 'I', 'name': 'Measure', 'isGeo': False, 'geoType': None}]
I want to create dictionary from this list
Need Values of 'id' as Id of dictionary & 'name' as Values of dictionary
Expected Results:-
ResultsDict = {'R':'Reporter', 'C':'Commodity', 'P':'Partner', 'TF':'Trade Flow', 'I':'Measure'}
Use dict comprehension:
d = {x['id']:x['name'] for x in dimensionList}
print (d)
{'R': 'Reporter', 'C': 'Commodity', 'P': 'Partner', 'TF': 'Trade Flow', 'I': 'Measure'}
You need to loop through the list of dictionaries, pulling out the bits you want and adding them to your new dictionary.
ResultsDict = {}
for dict_item in dimensionList:
id = dict_item ['id']
name = dict_item ['name']
ResultsDict[id] = name
print(ResultsDict)
Related
I am using the AccuWeather RESTFul API to get the current weather conditions in the top 50 cities. One object of the JSON response looks like this:
{'Key': '28143', 'LocalizedName': 'Dhaka', 'EnglishName': 'Dhaka', 'Country': {'ID': 'BD', 'LocalizedName': 'Bangladesh', 'EnglishName': 'Bangladesh'}, 'TimeZone': {'Code': 'BDT', 'Name': 'Asia/Dhaka', 'GmtOffset': 6.0, 'IsDaylightSaving': False, 'NextOffsetChange': None}, 'GeoPosition': {'Latitude': 23.7098, 'Longitude': 90.40711, 'Elevation': {'Metric': {'Value': 5.0, 'Unit': 'm', 'UnitType': 5}, 'Imperial': {'Value': 16.0, 'Unit': 'ft', 'UnitType': 0}}}, 'LocalObservationDateTime': '2021-10-09T13:11:00+06:00', 'EpochTime': 1633763460, 'WeatherText': 'Mostly cloudy', 'WeatherIcon': 6, 'HasPrecipitation': False, 'PrecipitationType': None, 'IsDayTime': True, 'Temperature': {'Metric': {'Value': 32.2, 'Unit': 'C', 'UnitType': 17}, 'Imperial': {'Value': 90.0, 'Unit': 'F', 'UnitType': 18}}, 'MobileLink': 'http://www.accuweather.com/en/bd/dhaka/28143/current-weather/28143?lang=en-us', 'Link': 'http://www.accuweather.com/en/bd/dhaka/28143/current-weather/28143?lang=en-us'}
Now I want to populate a dictionary with 1) "EnglishName", 2) "WeatherText", and 3) "Temperature (Celsius)".
I do manage to get a key-value pair with "EnglishName" and "WeatherText" as below:
weatherResponse = result.json()
mydictionary = dict()
for p in weatherResponse:
print(p["EnglishName"])
print(p["LocalObservationDateTime"])
print(p["WeatherText"])
temp_C = list(p["Temperature"]["Metric"].values())[0]
print(f"Temperature in Celsius: {temp_C}")
print("--------")
mydictionary[p["EnglishName"]] = p["WeatherText"]
How can I assign the "temp_C" value of each key to the dictionary as well?
I tried the append function but that does not work.
Any help is appreciated!
Instead of adding only one value p["WeatherText"] to your dictionary you can add multiple through use of tuples, like (a,b). Please see the below line.
mydictionary[p["EnglishName"]] = (p["WeatherText"], p["Temperature"]["Metric"]["Value"])
This above line you can use to assign to your dictionary key multiple values, sample output from this:
{'Dhaka': ('Mostly cloudy', 32.2)}
You can read tuples just like lists
mydictionary["Dhaka"][0] # This for getting the text
mydictionary["Dhaka"][1] # This for getting the value
Also tuples may look similar to lists but in this case it is recommended to use tuples because lists should store same data type values and tuples can store multiple datatype values.
I want to populate a dictionary with 1) "EnglishName", 2) "WeatherText", and 3) "Temperature (Celsius)".
See below
data = [{
'Key': '28143',
'LocalizedName': 'Dhaka',
'EnglishName': 'Dhaka',
'Country': {
'ID': 'BD',
'LocalizedName': 'Bangladesh',
'EnglishName': 'Bangladesh'
},
'TimeZone': {
'Code': 'BDT',
'Name': 'Asia/Dhaka',
'GmtOffset': 6.0,
'IsDaylightSaving': False,
'NextOffsetChange': None
},
'GeoPosition': {
'Latitude': 23.7098,
'Longitude': 90.40711,
'Elevation': {
'Metric': {
'Value': 5.0,
'Unit': 'm',
'UnitType': 5
},
'Imperial': {
'Value': 16.0,
'Unit': 'ft',
'UnitType': 0
}
}
},
'LocalObservationDateTime': '2021-10-09T13:11:00+06:00',
'EpochTime': 1633763460,
'WeatherText': 'Mostly cloudy',
'WeatherIcon': 6,
'HasPrecipitation': False,
'PrecipitationType': None,
'IsDayTime': True,
'Temperature': {
'Metric': {
'Value': 32.2,
'Unit': 'C',
'UnitType': 17
},
'Imperial': {
'Value': 90.0,
'Unit': 'F',
'UnitType': 18
}
},
'MobileLink': 'http://www.accuweather.com/en/bd/dhaka/28143/current-weather/28143?lang=en-us',
'Link': 'http://www.accuweather.com/en/bd/dhaka/28143/current-weather/28143?lang=en-us'
}]
filtered_data = [{'EnglishName':e.get('EnglishName','NA'),'WeatherText':e.get('WeatherText','NA'),'temp_C':e.get('Temperature').get('Metric').get('Value')} for e in data]
print(filtered_data)
output
[{'EnglishName': 'Dhaka', 'WeatherText': 'Mostly cloudy', 'temp_C': 32.2}]
How to Find the dictionary from List which has key-pair 'isGeo':True
dimensions = [{'key': 2600330, 'id': 'location', 'name': 'Location', 'isGeo': True, 'geoType': 'region'}, {'key': 2600340, 'id': 'subject', 'name': 'Subject', 'isGeo': False, 'geoType': None}, {'key': 2600350, 'id': 'measure', 'name': 'Measure', 'isGeo': False, 'geoType': None}]
I want to below result:
{'key': 2600330, 'id': 'location', 'name': 'Location', 'isGeo': True, 'geoType': 'region'}
Use next with a generator expression:
res = next((d for d in dimensions if d['isGeo']), None)
{'key': 2600330, 'id': 'location', 'name': 'Location', 'isGeo': True, 'geoType': 'region'}
Since you tagged pandas, you can also use Pandas:
import pandas as pd
df = pd.DataFrame(dimensions)
res = df.loc[df['isGeo']].iloc[0].to_dict()
The above solutions assume you want only the first dictionary satisfying your condition. If you want a list of dictionaries use:
res = [d for d in dimensions if d['isGeo']]
res = df.loc[df['isGeo']].to_dict('records')
Another way is list comprehension
dimensions = [{'key': 2600330, 'id': 'location', 'name': 'Location', 'isGeo': True, 'geoType': 'region'}, {'key': 2600340, 'id': 'subject', 'name': 'Subject', 'isGeo': False, 'geoType': None}, {'key': 2600350, 'id': 'measure', 'name': 'Measure', 'isGeo': False, 'geoType': None}]
geoDimension = [dimension for dimension in dimensions if dimension['isGeo']][0]
Output : {'key': 2600330, 'id': 'location', 'name': 'Location', 'isGeo': True, 'geoType': 'region'}
I have a list of dictionaries, and I want to cycle through them and replace one of the values. The value I'm replacing is a dictionary, and I want to replace it with one of the values from the same dictionary.
Below is one of the dictionaries in the list.
{'id': '123abc',
'name': 'Metrics',
'rows': 0,
'columns': 0,
'owner': {'id': 123, 'name': 'John Doe'},
'dataCurrentAt': '2017-03-24T14:32:33Z',
'createdAt': '2017-03-24T14:32:33Z',
'pdpEnabled': False}
So I'm trying to replace the entire 'owner' value with just 'name' from the 'owner' dictionary. I hope that makes sense. Below is the section of the Python script where I have attempted to do this.
for dictionary in dataset_list:
for key, value in dictionary.items():
if key == "owner":
owner = value.get("name")
value = owner
If I understand you correctly, all what you need to do is:
dictionary["owner"] = dictionary["owner"]["name"]
This will change the value of the key "owner", to the value of the key "name".
A = {'id': '123abc', 'name': 'Metrics', 'rows': 0, 'columns': 0, 'owner': {'id': 123, 'name': 'John Doe'}, 'dataCurrentAt': '2017-03-24T14:32:33Z', 'createdAt': '2017-03-24T14:32:33Z', 'pdpEnabled': False}
A["owner"] = A["owner"]["name"]
print A
Output:
{'rows': 0, 'createdAt': '2017-03-24T14:32:33Z', 'name': 'Metrics', 'pdpEnabled': False, 'owner': 'John Doe', 'id': '123abc', 'columns': 0, 'dataCurrentAt': '2017-03-24T14:32:33Z'}
You can try:
>>> dataset_list = {'id': '123abc', 'name': 'Metrics', 'rows': 0, 'columns': 0, 'owner': {'id': 123, 'name': 'John Doe'}, 'dataCurrentAt': '2017-03-24T14:32:33Z', 'createdAt': '2017-03-24T14:32:33Z', 'pdpEnabled': False}
>>> for k,v in dataset_list.iteritems():
if k == "owner":
owner = v["name"]
dataset_list[k] = owner
>>> dataset_list
{'rows': 0, 'createdAt': '2017-03-24T14:32:33Z', 'name': 'Metrics', 'pdpEnabled': False, 'owner': 'John Doe', 'id': '123abc', 'columns': 0, 'dataCurrentAt': '2017-03-24T14:32:33Z'}
for dictionary in dataset_list:
for key, value in dictionary.items():
if key == "owner":
dictionary["owner"] = dictionary["owner"]["name"]
elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'},
'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}}
Add an is_noble_gas boolean entry to the hydrogen and helium dictionaries.
You should access the dictionary and add is_noble_gas as a new key to the dictionary as follows.
>>> elements['hydrogen']['is_noble_gas'] = False
>>> elements['helium']['is_noble_gas'] = True
elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'}, 'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}}
noble_dict = { "hydrogen": False, "helium": True }
for noble in noble_dict:
elements[ noble ][ "is_noble_gas" ] = noble_dict[ noble ]
{'helium': {'symbol': 'He', 'number': 2, 'weight': 4.002602, 'is_noble_gas': True}, 'hydrogen': {'symbol': 'H', 'number': 1, 'weight': 1.00794, 'is_noble_gas': False}}
elements['hydrogen']['is_noble_gas'] = False
elements['hydrogen']['is_noble_gas'] = True
In a list containing dictionaries, how do I split it based on unique values of dictionaries? So for instance, this:
t = [
{'name': 'xyz', 'value': ['K','L', 'M', 'N']},
{'name': 'abc', 'value': ['O', 'P', 'K']}
]
becomes this:
t = [
{'name': 'xyz', 'value': 'K'},
{'name': 'xyz', 'value': 'L'},
{'name': 'xyz', 'value': 'M'},
{'name': 'xyz', 'value': 'N'},
{'name': 'abc', 'value': 'O'},
{'name': 'xyz', 'value': 'P'},
{'name': 'xyz', 'value': 'K'}
]
You can do this with a list comprehension. Iterate through each dictionary d, and create a new dictionary for each value in d['values']:
>>> t = [ dict(name=d['name'], value=v) for d in t for v in d['value'] ]
>>> t
[{'name': 'xyz', 'value': 'K'},
{'name': 'xyz', 'value': 'L'},
{'name': 'xyz', 'value': 'M'},
{'name': 'xyz', 'value': 'N'},
{'name': 'abc', 'value': 'O'},
{'name': 'abc', 'value': 'P'},
{'name': 'abc', 'value': 'K'}]