Member-only story

7 Python Dictionary Insights That Surprised Me!

Elshad Karimov
1 min readDec 25, 2023
  1. Merge Dictionaries with Ease:
  • Use the ** syntax for a quick merge:
d1 = {'a':1, 'b':2}
d2 = {'c':3, 'd':4}
d3 = {**d1, **d2}
# Output: {'a':1, 'b':2, 'c':3, 'd':4}

2. Safe Key Access with get:

  • Avoid KeyError by using get:
d = {'apple':4, 'orange':5}
print(d.get('pineapple', 100)) # Output: 100

3. Updating Dictionaries:

  • Combine dictionaries using update:
d1.update(d2)
# d1 now includes d2's key-value pairs

4. Class vs. Instance Dictionaries:

  • Instance attributes in .__dict__, class attributes in .__dict__ as a mappingproxy.

5. Iterating Made Simple:

  • Use keys(), values(), and items() for efficient iteration.

6. Efficient Dictionary Typing:

  • Shortcut for creating dictionaries:
d = dict(apple=4, orange=5, pear=6)

7. Quick Dictionary Initialization:

  • fromkeys for setting up default values:
fruits = ['apple', 'orange', 'pear']
d = dict.fromkeys(fruits, 5)

These insights have transformed my Python coding experience.

If you found them helpful:

  • Show some love with a 50-clap
  • Drop a comment.
  • Share your favorite part!

Discover more in my online courses at Appmillers

Connect on LinkedIn: Elshad Karimov

--

--

Elshad Karimov
Elshad Karimov

Written by Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers

No responses yet