Mathew K Analytics

Lesson 55 · Python for Data Science

5 - Survey Analysis in Python: Statistical Techniques for Data Science

Welcome! Today we will learn how to use Python for basic survey analysis. Analyzing survey data helps find trends, discover patterns, and answer real…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb
 

Survey Analysis in Python#

Welcome! Today we will learn how to use Python for basic survey analysis.

Analyzing survey data helps find trends, discover patterns, and answer real questions.

We will start with simple Python basics, and step-by-step build towards analyzing a sample survey.

No experience neededjust curiosity! Let us begin.

What is Survey Data?#

Survey data is information collected by asking people questions.

We can collect answers about favorite foods, study habits, hobbies, and more.

Analyzing this data can show us what most people like or need.

# Let us make a sample survey data set using a list of dictionaries.
survey_data = [
    {'name': 'Alice', 'age': 25, 'favorite_color': 'blue', 'likes_pizza': True},
    {'name': 'Bob', 'age': 30, 'favorite_color': 'green', 'likes_pizza': False},
    {'name': 'Cathy', 'age': 22, 'favorite_color': 'red', 'likes_pizza': True},
    {'name': 'Dan', 'age': 28, 'favorite_color': 'blue', 'likes_pizza': True},
    {'name': 'Eva', 'age': 24, 'favorite_color': 'purple', 'likes_pizza': False},
]

print('Here is our sample survey data:')
for entry in survey_data:
    print(entry)
    
Here is our sample survey data:
{'name': 'Alice', 'age': 25, 'favorite_color': 'blue', 'likes_pizza': True}
{'name': 'Bob', 'age': 30, 'favorite_color': 'green', 'likes_pizza': False}
{'name': 'Cathy', 'age': 22, 'favorite_color': 'red', 'likes_pizza': True}
{'name': 'Dan', 'age': 28, 'favorite_color': 'blue', 'likes_pizza': True}
{'name': 'Eva', 'age': 24, 'favorite_color': 'purple', 'likes_pizza': False}
# How many responses are there?
count = len(survey_data)
print('Number of survey responses:', count)
Number of survey responses: 5

Why Use Lists and Dictionaries?#

Lists let us store many answers in one place.

Dictionaries let us label each answer neatly.

This combo makes it easy to work with real survey data.

# Let us find the average age.
ages = []
for entry in survey_data:
    ages.append(entry['age'])

average_age = sum(ages) / len(ages)
print('Average age is:', average_age)
Average age is: 25.8
# Which color is most popular?
color_count = {}
for entry in survey_data:
    color = entry['favorite_color']
    if color not in color_count:
        color_count[color] = 1
    else:
        color_count[color] += 1

print('Color counts:', color_count)
Color counts: {'blue': 2, 'green': 1, 'red': 1, 'purple': 1}
# Let us find out who likes pizza.
pizza_lovers = []
for entry in survey_data:
    if entry['likes_pizza']:
        pizza_lovers.append(entry['name'])

print('People who like pizza:', pizza_lovers)
People who like pizza: ['Alice', 'Cathy', 'Dan']
# Let us filter survey data by age using input()
age_limit = int(input('Enter age limit to find participants older than: '))
older_participants = []
for entry in survey_data:
    if entry['age'] > age_limit:
        older_participants.append(entry['name'])

print('Participants older than', age_limit, ':', older_participants)
Participants older than 24 : ['Alice', 'Bob', 'Dan']
 
# What if someone did not answer one question?
survey_data.append({'name': 'Frank', 'age': 27, 'favorite_color': None, 'likes_pizza': True})
favorite_colors = []
for entry in survey_data:
    if entry['favorite_color'] is not None:
        favorite_colors.append(entry['favorite_color'])

print('Favorite colors with missing values skipped:', favorite_colors)
Favorite colors with missing values skipped: ['blue', 'green', 'red', 'blue', 'purple']
# Let us update Eva's favorite color to 'pink'.
for entry in survey_data:
    if entry['name'] == 'Eva':
        entry['favorite_color'] = 'pink'

print("Eva's updated survey info:", [e for e in survey_data if e['name'] == 'Eva'])
Eva's updated survey info: [{'name': 'Eva', 'age': 24, 'favorite_color': 'pink', 'likes_pizza': False}]
# Removing Frank's answer since it was blank
survey_data = [entry for entry in survey_data if entry['name'] != 'Frank']
print('Updated survey_data after removing Frank:')
for entry in survey_data:
    print(entry)
    
Updated survey_data after removing Frank:
{'name': 'Alice', 'age': 25, 'favorite_color': 'blue', 'likes_pizza': True}
{'name': 'Bob', 'age': 30, 'favorite_color': 'green', 'likes_pizza': False}
{'name': 'Cathy', 'age': 22, 'favorite_color': 'red', 'likes_pizza': True}
{'name': 'Dan', 'age': 28, 'favorite_color': 'blue', 'likes_pizza': True}
{'name': 'Eva', 'age': 24, 'favorite_color': 'pink', 'likes_pizza': False}

Simple Built-in Functions for Analysis#

  • max() finds the highest value.
  • min() finds the lowest value.
  • set() removes duplicates.

Let us apply these to our survey!

# Let us find oldest and youngest participant.
ages = [entry['age'] for entry in survey_data]
print('Oldest:', max(ages))
print('Youngest:', min(ages))
Oldest: 30
Youngest: 22
# Gather all unique favorite colors.
unique_colors = set(entry['favorite_color'] for entry in survey_data)
print('Unique favorite colors:', unique_colors)
Unique favorite colors: {'pink', 'red', 'green', 'blue'}
# Looping with enumerate for more info
for index, entry in enumerate(survey_data):
    print('Entry number', index + 1, 'belongs to', entry['name'])
    
Entry number 1 belongs to Alice
Entry number 2 belongs to Bob
Entry number 3 belongs to Cathy
Entry number 4 belongs to Dan
Entry number 5 belongs to Eva
# List comprehensions: shorter way to get names who like pizza
pizza_lovers = [entry['name'] for entry in survey_data if entry['likes_pizza']]
print('Pizza lovers using list comprehension:', pizza_lovers)
Pizza lovers using list comprehension: ['Alice', 'Cathy', 'Dan']
# Sorting: order by age, youngest first
sorted_by_age = sorted(survey_data, key=lambda x: x['age'])
print('Survey sorted by age:')
for entry in sorted_by_age:
    print(entry['name'], entry['age'])
    
Survey sorted by age:
Cathy 22
Eva 24
Alice 25
Dan 28
Bob 30
# Filtering: only people who do not like pizza
not_pizza = [entry['name'] for entry in survey_data if not entry['likes_pizza']]
print('People who do not like pizza:', not_pizza)
People who do not like pizza: ['Bob', 'Eva']
# Mini-project: Simple summary of the survey
summary = {
    'total_people': len(survey_data),
    'average_age': round(sum(entry['age'] for entry in survey_data) / len(survey_data), 1),
    'most_popular_color': max(
        set(entry['favorite_color'] for entry in survey_data),
        key=lambda c: [entry['favorite_color'] for entry in survey_data].count(c)
    ),
    'pizza_lovers': len([entry for entry in survey_data if entry['likes_pizza']])
}
print('Survey Summary:')
for k, v in summary.items():
    print(k, ':', v)
    
Survey Summary:
total_people : 5
average_age : 25.8
most_popular_color : blue
pizza_lovers : 3
# Mini-project, part 2: Ask user for a color and count who chose it
target_color = input('Type a color to check how popular it was: ')
color_count = 0
for entry in survey_data:
    if entry['favorite_color'] == target_color:
        color_count += 1

print(target_color, 'was chosen by', color_count, 'participant(s).')
blue was chosen by 2 participant(s).
 
# Best practice: handle keys safely to avoid errors
for entry in survey_data:
    color = entry.get('favorite_color', 'No answer')
    print(entry['name'], 'picked', color)
    
Alice picked blue
Bob picked green
Cathy picked red
Dan picked blue
Eva picked pink
# A common mistake: misspelled keys cause errors
try:
    for entry in survey_data:
        print(entry['fav_color'])  # This key does not exist
except KeyError:
    print('Oops! Key does not exist. Check your spelling.')
    
Oops! Key does not exist. Check your spelling.
# Extra tip: make a quick stats table for all colors
color_stats = {}
for entry in survey_data:
    color = entry['favorite_color']
    color_stats[color] = color_stats.get(color, 0) + 1

for color, count in color_stats.items():
    print('Color:', color, '| Count:', count)
    
Color: blue | Count: 2
Color: green | Count: 1
Color: red | Count: 1
Color: pink | Count: 1

Challenge Exercise#

Try editing the code to analyze another question.

For example: Who is the youngest pizza lover?

What is the most common first letter in participant names?

Play and practicethe best way to learn is by doing!

Recap#

Today you learned how to:

  • Store and view survey results
  • Count and filter answers
  • Handle missing data
  • Use built-in Python functions for analysis
  • Summarize and present survey findings

Survey analysis helps us understand the people around us and make better choices!

Thank You for Learning Survey Analysis!#

If you enjoyed this video, please like, comment your favorite new skill, and subscribe for more Python lessons.

Share it with friends who want to learn Python or do data analysishelp others join in the fun.

Happy coding and see you next time!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.