Performing conditional operations on a collection of dictionaries in Python

Is there a more efficient way to sum the ages of all males in this list of dictionaries?

list_of_dicts= [  
              {"Name": "Ethan", "Gender": "male", "Age": 11},
              {"Name": "Nathan", "Gender": "male", "Age": 6},
              {"Name": "Sophie", "Gender": "female", "Age": 14},
              {"Name": "Patrick", "Gender": "male", "Age": 11}
]

The code below gets the total male age, but is there a more Pythonic/compact approach? Perhaps something like an SQL query for a list of dictionaries?

total_male_age = 0

for dict in list_of_dicts: 
    if dict.get("Gender") == "male":
        total_male_age = total_male_age + dict.get("Age")  

#total_male_age  = 28

Answer №1

What do you think of this approach?

>>> sum(d['Years'] for d in list_of_dicts if d['Category'] == 'A')
45

In this code snippet, the sum function is being used on a generator expression that filters dictionaries based on the condition where Category is equal to "A".

If you're interested in learning more, you can refer to PEP 289 for additional examples.

To calculate a product instead of a sum:

import numpy as np
np.product([d['Years'] for d in list_of_dicts if d['Category'] == 'A'])

Alternatively, if you prefer working with Python's standard library:

from functools import reduce
from operator import mul
reduce(mul, (d['Years'] for d in list_of_dicts if d['Category'] == 'A'), 1)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Python - Retrieve data from a dataframe (JSON)

After taking a break from coding for some time, I am now diving back in as a beginner. I am currently using the requests library to fetch JSON data from the Incapsula API in order to collect stats about website traffic. My goal is to extract and write the ...

Error: Unexpected data type encountered. Expected an array but found a string instead at line 1, column 2

I have tried multiple suggestions from similar questions but none of them have helped. How can I successfully execute this test? @Test fun isJsonCorrectPersonConvert() { val gson = GsonBuilder().create() val json = gson.toJson("[{\"Id\": ...

What could be causing the select2 to not display the most up-to-date information in the control?

I have implemented a progressive search feature but it seems that the data returned is not populating the control properly. $("#selUser").select2({ ajax: { url: "/M01EngineeringData/GetFunctionalLocations", ty ...

What is the best way to include an image link in a JSON file using Nuxt.js?

I am working with nuxtjs and I have a file named data.json in the root directory. I am trying to add an image link in this JSON file, but it is not recognizing it. Here is my code: { "id": 1, "cardImg": "./assets/images/ima ...

Transform JSON data into CSV format using jq

{ "Users": [ { "Attributes": [ { "Name": "sub", "Value": "1" }, { ...

Creating a dynamic trio of graphs with HTML5, CSS3, and Vanilla JavaScript

I successfully created a tree graph using HTML5 and CSS3, but currently the nodes are static. I am looking to enhance the graph by making it dynamic. By dynamic, I mean that if the number of nodes increases or there are multiple children added, the graph ...

Decomposing the Retrofit response.body()

I am having difficulties with implementing Retrofit and understanding how to interpret the response body. I believe that there might be an issue with mapping my JSON data to POJO because the output is not what I expected when I print it out in the log. He ...

Python Selenium is unable to locate the Password ID

I am fairly new to Python and Selenium, attempting to develop a program that can log in to a Microsence network outlet. The browser opens successfully and I use the built-in API to access Firefox, but Selenium is unable to locate the Password ID for loggin ...

What distinguishes {key:" "} from {key:" "}, when it comes to JSON files?

I have been working on implementing validation using express Router. The issue I encountered is that when I pass {title:""}, the express-validator does not throw an error. However, when I pass {title:" "}, it works properly. exports.postValidatorCheck = [ ...

Effective ways to extract and store information from a JSON file

I am looking to create a JSON file using Node.js, but as a beginner, I have no clue how to do it. The issue arises when attempting to add data to the JSON file. Rather than increasing, the data gets overwritten. For instance, if I have data "a" (total dat ...

Is randomly pairing 2 datapairs after slicing a JSON array easy or challenging?

There is a JSON file containing an unlimited number of users [{ "fname": "Hubert", "lname": "Maier", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bd ...

Support for UTF-8 encoding in JsonObjectRequests within the Volley library

I am working with a utf-8 json file and I need to ensure it is properly displayed with utf-8 support. output = (TextView) view.findViewById(R.id.jData); JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, loginURL, null, new ...

The Django annotate function does not support accessing a floatfield within a model

I am attempting to add annotations to a queryset with the distances between each object and a location provided by the user. This is what I have implemented so far: lat1 = request.POST['lat'] lon1 = request.POST['lon'] locations = Loc ...

What is the best way to retrieve a subprocess in a Flask application?

I have a question regarding my Python Flask script. I am fairly new to Python and Flask, so please bear with me. The second decorator in my code is supposed to return the subprocess to the /results page. While the ping test does print in the terminal, I ...

Encountered an Unpredictable SyntaxError: Is this a Cross-Domain Problem?

I have been attempting to connect with the Indian Railway API using Ajax in order to retrieve data in JSON format. Below is the code I am using: <!DOCTYPE> <html> <head> <meta charset="UTF-8"> <script src="https://ajax.googleap ...

Executing multiple instances of ActionChains in SeleniumWould you like to learn how

Having issues with my Selenium script that is supposed to repeatedly click on a cookie on a webpage. However, it only clicks once even though I have wrapped it in a loop. Can someone please help me figure out what I am doing wrong? from selenium import w ...

Steps for eliminating unicode characters from a dataset using Pandas in Python

My dataset named rssfeeds has some unusual characters, how can I remove these unicodes and replace them with their original values? Here is a link to view my dataset: https://i.stack.imgur.com/CtYG0.png Any help would be greatly appreciated. ...

Creating specifications for query parameters in Loopback that are essential for handling CRUD operations

Our journey with Loopback has been successful thus far, but we are now looking to enhance our API documentation by including query parameters. In the swagger.json file, there could be a section that resembles this: { "swagger": "2.0", "i ...

Tips for modifying JSON property names during the parsing process

As outlined in the JSON.parse documentation, a reviver function can be utilized to modify the value of each property within the JSON data. Here is an example: JSON.parse('{"FirstNum": 1, "SecondNum": 2, "ThirdNum": 3}', function(k, v) { return ...

Encoding a string in JSON that contains the "#" symbol along with other special characters

The client side javascript code I have is as follows: <html> <script type="text/javascript" src="js/jquery.min.js"></script> <script> $(document).ready(function() { //var parameters = "a=" + JSON.stringify( ...