简体   繁体   中英

Using append to get data from a nested list

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM