Using append to get data from a nested list - python

Currently my code is like this:
.append("Last Name {}, First Name {} Stats: {}".format(result["L_Name"], result["F_Name"], result["Stats"]))
this code works but the output isn't exactly the ones I want the code to display.
the problem is that the Stats has another list
L_Name: Doe
F_Name: John
Contribution:
Month
Value
Returns
is there a way to just pick out only the Value from the Stats by just adding or changing something in my append?
specifically in this part?
, result["Stats"]))

If you are only after one value of Stats, you can get the value at a certain index. Assuming Value is at index 1 and Stats is a standard Python list:
, result["Stats"][1]))

Notice that you can access the items of the JSON structure in the format string itself. This is clearer than using positional arguments if the format string is very complicated. Additionally, you can pass the whole dictionary into format_map:
l.append("Last Name {L_Name}, First Name {F_Name} Stats: {Stats[Value]}"
.format_map(result))
(In Python 2, format_map doesn't exist, use format(**result) instead.

In the future please consider posting working code only so we can reproduce your issue. I am going to assume result['stats'] is a dictionary and the bulleted list are key:value pairs.
You can access the "Contribution" key of your result["Stats"] dictionary which results in list. You can then slice the second element of the list with [1].
_.append("Last Name {}, First Name {} Stats: {}".format(
result["L_Name"],
result["F_Name"],
result["Stats"]["Contribution"][1]))
This assumes result['stats'] looks like:
result['stats'] = {
'L_Name': 'Doe',
'F_Name': 'John',
'Contribution': [Month, Value, Returns]}

Thanks everyone I was able to get a hint from your answers
result["Stats"]["Contribution"][1]
worked well for me

Related

Looping through list to print each value from each key in loop

I have put together a script to output all fields from a json file.
I have running into issues getting it to print each finding from highsev and specifically the id field from each finding.
Here is the code:
json_object=json.load(f)
vulnsBySeverity["HIGHSEVERITY"] = []
for result in json_object['results']:
vulnsBySeverity["HIGHSEVERITY"] = [vuln for vuln in result['vulnerabilities'] if vuln["severity"] == "high"]
highsev=vulnsBySeverity["HIGHSEVERITY"]
print("HIGH VULNS were")
for finding in highsev:
print(highsev[finding]['id'])
Its complaining :
TypeError: list indices must be integers or slices, not dict
I think I understand what its saying that finding call in the print() has to be a int or slice im just wondering how i can do that, as finding contains this:
{'id': 'CVE-2020-15999'}
Im simply just trying to loop through highsev and output the value of id in a loop.
What might i be doing wrong here? can someone please help
You're already looping through highsev with your for finding in highsev:
If your highsev list contains dictionaries like this {'id': 'CVE-2020-15999'}, you can do this:
for finding in highsev:
print(finding['id'])
You can change last line to:
print(finding['id'])
As you are looping through highsev.

Adding a new dictionary item to a nested dictionary

cities={
'city1':{
'name':'sydney',
'country':'australia',
'desc':'beautiful'
},
'city2':{
'name':'toronto',
'country':'canada',
'desc':'amazing',
}
}
cities['city3']:"{'name':'Tokyo','country':'japan','desc':'lots of earthquakes’}"
for keys,values in cities.items():
print(f"{keys}--->{values}”)
This is my code. I am new to python and learning dictionaries as of now. I am trying to add a dictionary to an existing dictionary but it doesn’t work. I have no errors and still only get the first two cities info. I think my syntax must be wrong. Can anyone help me with this please>?
Output:
Try to change your insertion code to:
cities['city3'] = {'name':'Tokyo','country':'japan','desc':'lots of earthquakes'}
You probably don't want to add it as a string, so leave away the quatation marks. Furthermore, there is an erroneous quatation mark at the end of the description.
Use Chainmap from collections, it chains all dictionary into one.
from collections import ChainMap
city3 = {'city3': {'name':'Tokyo','country':'japan','desc':'lots of earthquakes'}}
cities = ChainMap(cities,city3)
print(dict(cities))

Indexing with string? [Python]

I am learning python this semester and I came across some code I do not understand well.
firstVal = examples[0][firstName]
where examples is list of dictionary
and firstName is a Str
Could someone help explain to me what it is doing?
Thanks!
Alright, so basically what it is doing is it is taking the first dictionary from the list of dictionaries, and accessing the value in the key for firstName.
For ex:
examples is some thing like:
[{'John': 'Doe', 'Jack': 'Peterson', 'Jake': 'Paul'}, {'Martin': 'Richardson', 'Luke': 'Skywalker', 'Logan': 'Paul'}]
Doing examples[0], get's you the first element of that list, which is: {'John': 'Doe', 'Jack': 'Peterson', 'Jake': 'Paul'}
Now, let's say firstName = 'Jack'.
Then, examples[0][firstName] is the same as examples[0]['Jack'] which is 'Peterson' because the value for the key 'Jack' is 'Peterson'
Please tell me if you need me to elaborate more ;)
The examples[0] is getting the first dictionary in the list of dictionaries examples. Then it is accessing the key defined by the string firstName.
For example,
examples = [{'1':2, '3':4}, {'5':6, '7':8}]
firstName = '1'
firstVal = examples[0][firstName] # will output 2
Let's take a look at it closely.
If examples is a list of dictionaries, then examples[0] must be the first dictionary in that list.
Then, we look for the key firstName in that dictionary.
We finally assign this value to firstVal.
So in a sentence, this line takes the first dictionary in the list, finds the value of the key firstName, and assigns it to firstVal.

How to iterate and extract data from this specific JSON file example

I'm trying to extract data from a JSON file with Python.
Mainly, I want to pull out the date and time from the "Technicals" section, to put that in one column of a dataframe, as well as pulling the "AKG" number and putting that in the 2nd col of the dataframe. Yes, I've looked at similar questions, but this issue is different. Thanks for your help.
A downNdirty example of the JSON file is below:
{ 'Meta Data': { '1: etc'
'2: etc'},
'Technicals': { '2017-05-04 12:00': { 'AKG': '64.8645'},
'2017-05-04 12:30': { 'AKG': '65.7834'},
'2017-05-04 13:00': { 'AKG': '63.2348'}}}
As you can see, and what's stumping me, is while the date stays the same the time advances. 'AKG' never changes, but the number does. Some of the relevant code I've been using is below. I can extract the date and time, but I can't seem to reach the AKG numbers. Note, I don't need the "AKG", just the number.
I'll mention: I'm creating a DataFrame because this will be easier to work with when creating plots with the data...right? I'm open to an array of lists et al, or anything easier, if that will ultimately help me with the plots.
akg_time = []
akg_akg = []
technicals = akg_data['Technicals'] #akg_data is the entire json file
for item in technicals: #this works
akg_time.append(item)
for item in technicals: #this not so much
symbol = item.get('AKG')
akg_akg.append(symbol)
pp.pprint(akg_akg)
error: 'str' object has no attribute 'get'
You've almost got it. You don't even need the second loop. You can append the akg value in the first one itself:
for key in technicals: # renaming to key because that is a clearer name
akg_time.append(key)
akg_akg.append(technicals[key]['AKG'])
Your error is because you believe item (or key) is a dict. It is not. It is just a string, one of the keys of the technicals dictionary, so you'd actually need to use symbols = technicals[key].get('AKG').
Although Coldspeed answer is right: when you have a dictionary you loop through keys and values like this:
Python 3
for key,value in technicals.items():
akg_time.append(key)
akg_akg.append(value["akg"])
Python 2
for key,value in technicals.iteritems():
akg_time.append(key)
akg_akg.append(value["akg"])

Dicts in Python

I have a multidimensionnal dict, I need to return a specific value.
ConsomRatio={"DAP_Local":[],"MAP11_52":[]}
ConsomRatio["DAP_Local"].append({"Ammonia":"0.229", "Amine":"0.0007"})
ConsomRatio["MAP11_52"].append({"Ammonia":"0.138", "Fuel":"0.003"})
print(ConsomRatio["DAP_Local"])
The result of the print is:
[{'Ammonia': '0.229', 'Amine': '0.0007'}]
My question is : Is there a way to return the value of "Ammonia" only, in "DAP_Local" ?
Thank you!
You can get to it like this. You're appending your dict to a list, so you must select the correct index in the list where the dict is located. In this case the first element in the list or index 0.
ConsomRatio["DAP_Local"][0]["Ammonia"]
By the way, depending on what you are trying to achieve you might wanna take a look at the other answers for different implementations of multi-dimensional dicts.
The other answers are of course correct, but have you considered using a "dict of dicts"? i.e.:
ConsomRatio={"DAP_Local":{},"MAP11_52":{}}
ConsomRatio["DAP_Local"].update({"Ammonia":"0.229", "Amine":"0.0007"})
ConsomRatio["MAP11_52"].update({"Ammonia":"0.138", "Fuel":"0.003"})
print ConsomRatio["DAP_Local"]["Ammonia"]
0.229
since print(ConsomRatio["DAP_Local"]) returns an array of length 1, you need to select the index 0, then key off the 'Ammonia' value as above.
if print(ConsomRatio["DAP_Local"]) returned a dict, then no need to have the [0] and print(ConsomRatio["DAP_Local"]['Amomonia']) would have worked
Why are you putting lists in your dict, anyhow? You can just use dicts inside your main dict.
You can have multidimensional dicts also without the lists, e.g.:
ConsomRatio = {}
ConsomRation["DAP_Local"] = {"Ammonia":"0.229", "Amine":"0.0007"}
ConsomRatio["MAP11_52"] = {"Ammonia":"0.138", "Fuel":"0.003"}
print(ConsomRatio["DAP_Local"]["Ammonia"])
will give the desired result without the extra effort with the list.
You can get even shorter in Python:
ConsomRatio = {
"DAP_Local": {"Ammonia":"0.229", "Amine":"0.0007"},
"MAP11_52" : {"Ammonia":"0.138", "Fuel":"0.003"},
}
print(ConsomRatio["DAP_Local"]["Ammonia"])
To also answer your latest question (in your second comment):
to_produce = 'DAP_Local'
ingredience = 'Ammonia'
print('To produce {to_produce} we need {amount} of {ingredience}'.format(
to_produce=to_produce, ingredience=ingredience,
amount=ConsomRatio[to_produce].get(ingredience, '0.0')))
I hope, that helps!
It gets even better:
for product, ingred_list in ConsomRatio.items():
for iname, ivalue in ingred_list.items():
print('To produce {to_produce} we need {amount} of {ingredience}'
.format(to_produce=product, ingredience=iname,
amount=ivalue))

Categories