Python
dictionary
programming
variables
coding tips

Simpler way to create dictionary of separate variables?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Creating a dictionary from separate variables is common in scripts and small automation tasks. The challenge is balancing convenience with readability and safety. A clear pattern prevents accidental leakage of unrelated variables and keeps code maintainable.

Explicit Mapping Is the Most Readable Default

The simplest and safest approach is explicit construction. It is easy to read, easy to review, and stable during refactoring.

python
1name = "Ava"
2age = 29
3city = "Toronto"
4
5payload = {
6    "name": name,
7    "age": age,
8    "city": city,
9}
10
11print(payload)

This is often better than dynamic introspection in production code because intent is obvious.

Controlled Dynamic Construction with Selected Keys

If many fields are involved, use a key list and locals or a source dictionary, but keep key selection explicit.

python
1def build_payload(name, age, city, country):
2    keys = ["name", "age", "city"]
3    scope = locals()
4    return {k: scope[k] for k in keys}
5
6
7print(build_payload("Ava", 29, "Toronto", "CA"))

This avoids accidental inclusion of helper variables and keeps behavior deterministic.

Dataclass-Based Pattern for Structured Data

For domain objects, dataclasses give stronger structure and cleaner conversion to dictionaries.

python
1from dataclasses import dataclass, asdict
2
3@dataclass
4class UserProfile:
5    name: str
6    age: int
7    city: str
8
9profile = UserProfile(name="Ava", age=29, city="Toronto")
10profile_dict = asdict(profile)
11print(profile_dict)

Dataclasses also integrate better with type checking and editor tooling.

Filtering Optional Values

In API payloads, you may want to include only non-empty values. Use a post-filter step to remove null-like entries.

python
1def compact_dict(data):
2    return {k: v for k, v in data.items() if v is not None and v != ""}
3
4raw = {
5    "name": "Ava",
6    "phone": "",
7    "email": None,
8    "city": "Toronto",
9}
10
11print(compact_dict(raw))

This keeps outgoing payloads concise while preserving explicit schema control.

Recommendation for Team Codebases

In collaborative projects, prefer explicit mapping or dataclass conversion. Reserve dynamic introspection for metaprogramming scenarios where schema is genuinely variable. This convention reduces debugging time because dictionary shape is obvious from code.

When dynamic behavior is required, keep a whitelist of keys and add unit tests that lock output shape. This catches regressions when parameter names evolve.

Team-Friendly Payload Construction Pattern

In API clients and ETL jobs, payload definitions evolve over time. Keep dictionary-building logic in one dedicated function per payload type, with clear defaults and validation. This gives you one stable contract and avoids scattered ad hoc dictionary literals across files. Add schema tests that assert required keys, optional keys, and value types. If you need conditional inclusion, implement it with named rules rather than implicit truthiness checks. For example, include phone only when explicitly provided, not merely when non-empty after trimming. This level of explicitness simplifies debugging and makes payload behavior predictable for downstream consumers. Over time, these conventions improve reliability more than any micro-optimization in dictionary creation syntax.

python
1def make_user_payload(name, age, city, phone=None):
2    data = {"name": name, "age": int(age), "city": city}
3    if phone is not None:
4        data["phone"] = phone
5    return data
6
7print(make_user_payload("Ava", "29", "Toronto"))

Verification Checklist

Write tests that assert key order if required by downstream consumers, and tests that reject unknown fields. This keeps payload construction deterministic as the codebase grows and more contributors modify request-building helpers.

Common Pitfalls

  • Using locals blindly and leaking temporary variables.
  • Building dictionaries dynamically without key whitelists.
  • Overusing one-liners that are compact but hard to read in reviews.
  • Skipping schema tests when payload shape is business-critical.

Document payload rules in code comments so API changes are reflected immediately in the construction helper.

Keep one example payload fixture in tests and compare exact dictionary output on each release.

Summary

  • Use explicit mapping for clarity and long-term maintainability.
  • Use selected-key dynamic mapping when scale requires it.
  • Prefer dataclasses for structured domain data.
  • Filter optional values intentionally.
  • Add tests that verify expected dictionary keys.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.