Fundamentals 12 min read

13 Essential Python List, Dictionary, and String Tricks Every Developer Should Know

This article presents thirteen practical Python techniques—including list merging, dictionary manipulation, string formatting, and file I/O—complete with clear explanations, ready‑to‑run code snippets, and visual results to help developers work more efficiently.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
13 Essential Python List, Dictionary, and String Tricks Every Developer Should Know

Python is one of the most popular programming languages today, widely used in data science, web development, game development, and many other fields because of its readability and high productivity.

List Operations (6 techniques)

1. Merge two lists into a dictionary

Combine two parallel lists so that the first list provides keys and the second provides values, typically using the built‑in zip function.

keys_list = ['A', 'B', 'C']
values_list = ['blue', 'red', 'bold']
# Method 1: zip + dict
dict_method_1 = dict(zip(keys_list, values_list))
# Method 2: dict comprehension with zip
dict_method_2 = {key: value for key, value in zip(keys_list, values_list)}
# Method 3: loop with zip
items_tuples = zip(keys_list, values_list)
dict_method_3 = {}
for key, value in items_tuples:
    if key in dict_method_3:
        pass
    else:
        dict_method_3[key] = value
print(dict_method_1)
print(dict_method_2)
print(dict_method_3)

Result:

2. Merge multiple lists into a single list of tuples

Collect several lists so that the first elements of each form the first tuple, the second elements form the second tuple, and so on.

def merge(*args, missing_val=None):
    max_length = max([len(lst) for lst in args])
    outList = []
    for i in range(max_length):
        outList.append([args[k][i] if i < len(args[k]) else missing_val for k in range(len(args))])
    return outList

merge([1,2,3], ['a','b','c'], ['h','e','y'], [4,5,6])

Result:

3. Sort a list of dictionaries

Sort dictionaries by a specific key using list.sort with a lambda or itemgetter.

dicts_lists = [
    {"Name": "James", "Age": 20},
    {"Name": "May", "Age": 14},
    {"Name": "Katy", "Age": 23}
]
# Method 1: sort by Age
dicts_lists.sort(key=lambda item: item.get("Age"))
# Method 2: sort by Name using itemgetter
from operator import itemgetter
f = itemgetter('Name')
dicts_lists.sort(key=f)

Result:

4. Sort a list of strings

Sort strings alphabetically, by length, or using locale‑aware comparison.

my_list = ["blue", "red", "green"]
# Alphabetical sort
my_list.sort()
# Sort by length
my_list = sorted(my_list, key=len)
# Locale‑aware sort
import locale
from functools import cmp_to_key
my_list = sorted(my_list, key=cmp_to_key(locale.strcoll))

Result:

5. Sort a list based on another list

Use zip to reorder one list according to the ordering defined by a second list of indices.

a = ['blue', 'green', 'orange', 'purple', 'yellow']
b = [3, 2, 5, 4, 1]
sortedList = [val for (_, val) in sorted(zip(b, a), key=lambda x: x[0])]
print(sortedList)

Result:

6. Map a list to a dictionary

Convert a list into a dictionary with numeric keys using zip and dict.

mylist = ['blue', 'orange', 'green']
mapped_dict = dict(enumerate(mylist))
print(mapped_dict)

Dictionary Operations (2 techniques)

7. Merge multiple dictionaries

Combine several dictionaries into one, preserving all keys (duplicates are aggregated into lists).

from collections import defaultdict

def merge_dicts(*dicts):
    mdict = defaultdict(list)
    for d in dicts:
        for key, value in d.items():
            mdict[key].append(value)
    return dict(mdict)

8. Invert a dictionary

Swap keys and values; values may become lists if they are not unique.

my_dict = {"brand": "Ford", "model": "Mustang", "year": 1964}
# Method 1
my_inverted_dict_1 = dict(map(reversed, my_dict.items()))
# Method 2 using defaultdict
from collections import defaultdict
my_inverted_dict_2 = defaultdict(list)
for k, v in my_dict.items():
    my_inverted_dict_2[v].append(k)
print(my_inverted_dict_1)
print(my_inverted_dict_2)

Result:

String Operations (3 techniques)

9. Use f‑strings for formatting

str_val = 'books'
num_val = 15
print(f'{num_val} {str_val}')
print(f'{num_val % 2 = }')
print(f'{str_val!r}')
price_val = 5.18362
print(f'{price_val:.2f}')
from datetime import datetime
date_val = datetime.utcnow()
print(f'{date_val=:%Y-%m-%d}')

Result:

10. Check for a substring in a list of strings

addresses = ["123 Elm Street", "531 Oak Street", "678 Maple Street"]
street = "Elm Street"
# Method 1
for address in addresses:
    if address.find(street) >= 0:
        print(address)
# Method 2
for address in addresses:
    if street in address:
        print(address)

Result:

11. Get the size of a string in bytes

str1 = "hello"
str2 = ""

def str_size(s):
    return len(s.encode('utf-8'))

print(str_size(str1))
print(str_size(str2))

Result:

Input/Output Operations (2 techniques)

12. Check if a file exists

# Method 1
import os
exists = os.path.isfile('/path/to/file')

# Method 2
from pathlib import Path
config = Path('/path/to/file')
if config.is_file():
    pass

13. Parse a CSV spreadsheet

import csv
csv_mapping_list = []
with open('/path/to/data.csv') as my_data:
    csv_reader = csv.reader(my_data, delimiter=",")
    line_count = 0
    for line in csv_reader:
        if line_count == 0:
            header = line
        else:
            row_dict = {key: value for key, value in zip(header, line)}
            csv_mapping_list.append(row_dict)
        line_count += 1

This collection of concise, ready‑to‑run examples equips Python learners with everyday tools for handling lists, dictionaries, strings, and file operations efficiently.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonStringCode Examplesprogramming fundamentalsListdictionaryfile-io
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.