Skip to main content
Python Lists and Dictionaries

Python Lists and Dictionaries

·346 words·2 mins·
Photo by Ed Robertson on Unsplash
This post covers practical Python snippets for manipulating lists and dictionaries. Whether you need to merge dictionaries, remove duplicates, sort data, or split lists into chunks, these examples will help streamline your workflow.

Merge dictionaries
#

d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "d": 4}
{**d1, **d2}
{"a": 1, "b": 2, "c": 3, "d": 4}

Since Python 3.9.0, an union operator has been introduced:

d1 | d2

Remove duplicates from a list of dictionaries
#

staff = [
    {"id": "00121", "name": "Jim"},
    {"id": "25065", "name": "Dwight"},
    {"id": "78541", "name": "Kevin"},
    {"id": "00145", "name": "Pam"},
    {"id": "05466", "name": "Toby"},
    {"id": "85546", "name": "Angela"},
    {"id": "78455", "name": "Erin"},
    {"id": "00145", "name": "Pam"},
]

list({person["id"]: person for person in staff}.values())

Sort list of dictionaries by attribute values
#

sorted(staff, key=lambda person: person["name"])

Sort dictionary by keys
#

d = {2:3, 1:89, 4:5, 3:0}
print({k:v for k,v in sorted(d.items())})
{1: 89, 2: 3, 3: 0, 4: 5}

Sort dictionary by values
#

d = {0: 500, 1: 225, 2: 312, 3: 4015, 4: 17}
print({k: d[k] for k in sorted(d, key=d.get)})
{4: 17, 1: 225, 2: 312, 0: 500, 3: 4015}

Get key of min / max value from dictionary
#

d = {0: 500, 1: 225, 2: 312, 3: 4015, 4: 17}
print(min(d, key=d.get))
print(max(d, key=d.get))
4
3

Split list into chunks
#

my_list = list(range(1, 10))
chunks_size = 3
print(
    [my_list[i:i + chunks_size]
    for i in range(0, len(my_list), chunks_size)]
)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Sort list of folders by number in name
#

import os

for i in range(1, 21):
    os.mkdir(f"test_{i}")

dirs = os.listdir()
dirs.sort()
print(dirs)
[
    "test_1",
    "test_10",
    "test_11",
    "test_12",
    "test_13",
    "test_14",
    "test_15",
    "test_16",
    "test_17",
    "test_18",
    "test_19",
    "test_2",
    "test_20",
    "test_3",
    "test_4",
    "test_5",
    "test_6",
    "test_7",
    "test_8",
    "test_9",
]
def by_numbers(s):
    # prepend 0 in case s doesn't contain any digit
    return int("0" + "".join(c for c in s if c.isdigit()))

dirs.sort(key=by_numbers)
print(dirs)
[
    "test_1",
    "test_2",
    "test_3",
    "test_4",
    "test_5",
    "test_6",
    "test_7",
    "test_8",
    "test_9",
    "test_10",
    "test_11",
    "test_12",
    "test_13",
    "test_14",
    "test_15",
    "test_16",
    "test_17",
    "test_18",
    "test_19",
    "test_20",
]