python
dictionary
variables
programming
coding

How can I get dictionary key as variable directly in Python not by searching from value?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Python, you can extract dictionary keys directly as variables using several techniques: unpacking with * or tuple assignment, iterating with for key in dict, converting to a list with list(dict.keys()), or using structured unpacking for known dictionaries. The approach depends on whether you want all keys, specific keys, or keys at certain positions. Since Python 3.7, dictionaries maintain insertion order, so extracting "the first key" or "the last key" is well-defined.

Unpacking Keys into Variables

When you know the dictionary structure, unpack keys directly:

python
1person = {"name": "Alice", "age": 30, "city": "New York"}
2
3# Unpack all keys into variables
4key1, key2, key3 = person
5print(key1, key2, key3)  # name age city
6
7# Unpack with * to collect remaining keys
8first, *rest = person
9print(first)  # name
10print(rest)   # ['age', 'city']

Iterating over a dictionary yields its keys by default. Tuple unpacking assigns each key to a variable in insertion order.

Getting a Specific Key by Position

python
1data = {"x": 10, "y": 20, "z": 30}
2
3# First key
4first_key = next(iter(data))
5print(first_key)  # x
6
7# Last key
8last_key = list(data)[-1]
9print(last_key)  # z
10
11# Nth key
12keys_list = list(data)
13second_key = keys_list[1]
14print(second_key)  # y
15
16# First and last using unpacking
17first, *_, last = data
18print(first, last)  # x z

next(iter(data)) is O(1) — it does not create a list. list(data)[-1] is O(n) because it builds the full list.

Converting Keys to a List

python
1config = {"host": "localhost", "port": 5432, "db": "myapp"}
2
3# Get all keys as a list
4keys = list(config.keys())
5print(keys)  # ['host', 'port', 'db']
6
7# Or equivalently
8keys = list(config)
9print(keys)  # ['host', 'port', 'db']
10
11# Access by index
12print(keys[0])  # host
13print(keys[2])  # db

Extracting Keys and Values Together

python
1person = {"name": "Alice", "age": 30, "city": "New York"}
2
3# Unpack items (key-value pairs)
4for key, value in person.items():
5    print(f"{key} = {value}")
6# name = Alice
7# age = 30
8# city = New York
9
10# Create separate variables for a known structure
11name_key, age_key, city_key = person.keys()
12print(name_key)  # name

Using Destructuring with Known Keys

When you know which keys exist, access them directly:

python
1data = {"x": 10, "y": 20, "z": 30}
2
3# Direct key access (most common)
4x_val = data["x"]
5y_val = data["y"]
6
7# Using operator.itemgetter for multiple values
8from operator import itemgetter
9
10x, y, z = itemgetter("x", "y", "z")(data)
11print(x, y, z)  # 10 20 30
12
13# Using get() with defaults
14value = data.get("missing_key", "default")
15print(value)  # default

Sometimes developers want to create variables named after dictionary keys:

python
1data = {"name": "Alice", "age": 30}
2
3# Works but NOT recommended — hard to debug
4for key, value in data.items():
5    locals()[key] = value
6# name and age are now local variables... maybe
7
8# Better: use the dictionary directly
9print(data["name"])  # Alice
10
11# Or use types.SimpleNamespace for attribute access
12from types import SimpleNamespace
13
14ns = SimpleNamespace(**data)
15print(ns.name)  # Alice
16print(ns.age)   # 30

locals() modification is not guaranteed to work in all Python implementations. Use SimpleNamespace or a dataclass instead.

Dataclass for Structured Dictionaries

python
1from dataclasses import dataclass
2
3@dataclass
4class Config:
5    host: str
6    port: int
7    db: str
8
9# Convert dict to dataclass
10config_dict = {"host": "localhost", "port": 5432, "db": "myapp"}
11config = Config(**config_dict)
12
13print(config.host)  # localhost
14print(config.port)  # 5432
15
16# Access the field names (keys)
17from dataclasses import fields
18key_names = [f.name for f in fields(config)]
19print(key_names)  # ['host', 'port', 'db']

Filtering Keys

python
1data = {"name": "Alice", "age": 30, "city": "New York", "score": 95}
2
3# Keys matching a condition
4string_keys = [k for k, v in data.items() if isinstance(v, str)]
5print(string_keys)  # ['name', 'city']
6
7# Keys starting with a prefix
8a_keys = [k for k in data if k.startswith("a")]
9print(a_keys)  # ['age']
10
11# Keys present in both dictionaries
12other = {"name": "Bob", "email": "[email protected]"}
13common_keys = data.keys() & other.keys()
14print(common_keys)  # {'name'}

dict.keys() returns a set-like view that supports intersection (&), union (|), and difference (-) operations.

Common Pitfalls

  • Modifying locals() to create variables from keys: Assigning to locals() inside a function is not guaranteed to create accessible local variables in CPython. Use SimpleNamespace(**data) or a dataclass for attribute-style access from dictionary data.
  • Assuming key order in Python 3.6 and earlier: Dictionary key order is only guaranteed from Python 3.7 onwards. In Python 3.6, CPython preserves insertion order as an implementation detail, but other implementations may not. Use collections.OrderedDict for guaranteed order on older versions.
  • Using list(dict.keys()) repeatedly for index access: Converting keys to a list every time you need positional access is O(n). If you need multiple positional lookups, create the list once and reuse it.
  • Unpacking into wrong number of variables: a, b = {"x": 1, "y": 2, "z": 3} raises ValueError: too many values to unpack. The number of variables must match the number of keys, or use * to collect extras.
  • Confusing dict.keys() view with a list: dict.keys() returns a view object that does not support indexing. keys[0] raises TypeError. Convert to a list first with list(dict.keys()) if you need index access.

Summary

  • Iterate over a dictionary to get keys: for key in dict yields keys in insertion order
  • Unpack keys into variables: a, b, c = dict assigns keys to variables
  • Get the first key with next(iter(dict)) — O(1) without creating a list
  • Convert to a list with list(dict) for index-based access
  • Use SimpleNamespace(**dict) or dataclasses for attribute-style access to dictionary data
  • dict.keys() returns a set-like view supporting intersection, union, and difference operations

Course illustration
Course illustration

All Rights Reserved.