• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
Data Dependence

Data Dependence

Learn about software development. Covering topics such as Coding in Python and JavaScript, developer productivity and more.

  • Home
  • Top Resources
  • Who Are You?
  • Show Search
Hide Search
You are here: Home / Programming / How to Write Beautiful Code with Pythonic Idioms | Dictionaries

How to Write Beautiful Code with Pythonic Idioms | Dictionaries

· · Leave a Comment

This is the forth in a series of posts on common pythonic idioms, so if you haven’t seen the previous two, you should definitely go and give them a read.

STEP ONE: MASTER DICTIONARIES, STEP TWO: TAKE OVER THE WORLD

OK, obviously you can’t take over the world with dictionaries, but mastering them will seriously up your programming game.

Dictionaries are a fairly large topic with many applications and ways to manipulate them. I won’t be covering everything about dictionaries in this post, but here are some pythonic idioms that I think are especially useful.

Looping over dictionary keys

One of the most basic things you can do with a dictionary is to loop over its keys. It’s also something that you will be doing very frequently, so let’s do it the Python way.

#How not to loop over dictionary keys
for k in dic.keys():
    print(k)
    
#How to loop over dictionary keys
for k in dic:
    print(k)

As shown above the preferred way to loop over keys in python is to actually not use the dictionary.keys() method. All that is needed is the reference to the dictionary.

Looping over key/value pairs

Another task you will often find yourself needing to do is looping over key/value pairs. As per usual with Python there are a couple of quick, easy and clean ways to do this.

#looping over keys
for k in dic:
    print(k)
    print(dic[k])
#looping over key/value pairs
for k, val in dic.items():
    print(k)
    print(val)

These are two different ways of looping over key/value pairs in a dictionary. The first loops over the keys in the dictionary then using the keys retrieves the values. The second loops over the items in the dictionary, that is they key/value pairs and unpacks them into two variables.

Using dictionary.get() to get values

What if you want to get the value associated with a key in a dictionary, but you don’t actually know if that key exists or not. Python has you covered.

#How to use get() to get values
val = dic.get('James', 'Could not be found')

If the key ‘James’ exists in the dictionary dic, this statement assigns the value that is paired with ‘James’ to the variable val. If the key ‘James’ doesn’t exist however, the default value, which is the second argument in the function call will be assigned. You can read more about get() in the Python documentation.

Deleting items that meet a certain criteria

I learnt this Python trick recently and absolutely love the power of it. Usually this kind of task would require a loop and conditionals. In Python, it’s just one line.

#Deleting keys that meet a certain criteria
dic = {k : dic[k] for k in dic if not len(k) < 5}

The syntax here is fairly simple too if you break it down. {key : value for key in dictionary [condition]}. The above statement creates a new dictionary that contains all key/value pairs in dic where the key has a length of less than 5.

Combining two lists into a dictionary

Say you have a list of given names and a list of surnames, but you want a dictionary of surname/given name pairs, what do you do? You zip them.

#Combining lists into a dictionary
f_names = ["Jamal", "Henry", "Phillip", "George"]
l_names = ["Moir", "Williams", "Clarke", "Smith"]
names = dict(zip(f_names, l_names))

This idiom here takes the lists f_names and l_names and combines to form a dictionary of last name/first name pairs. Quick, simple and like a lot of other Python idioms, one line. You can read more about zip() in the Python documentation.

There we have it, some pythonic idioms for dictionaries that I have found to be particularly useful, hopefully they will help you level up your python code too.

If you would like to know more about the dictionary data structure itself in Python, you can take a look at the documentation here.

Don't forget to share and follow!

Remember, don't forget to share this post so that other people can see it too! Also, make sure you subscribe to this blog's mailing list and follow me on Twitter so that you don't miss out on any useful posts!

I read all comments, so if you have something to say, something to share or questions and the like, leave a comment below!

‘Ello, I’m Jamal – a Tokyo-based, indie-hacking, FinTech software developer with a dependence on data.

I write Shakespeare-grade code, nowadays mostly in Python and JavaScript and productivity runs in my veins.

I’m friendly, so feel free to say hello!

Twitter is the best place for a chat.

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Pocket (Opens in new window)

Related

Programming dictionaries, idioms, python, pythonic

Primary Sidebar

LEVEL UP with the Data Dependence Newsletter! Subscribe!


Top Posts & Pages

  • How to Find Unclosed Tags and Brackets Using a Stack
  • How to Build a GUI in Python 3.5
  • Mocking in Python - How to Bypass Expensive and External Code Within Your Tests
  • How to Logically Group Your Python Code into Modules
  • A Quick Guide to Slicing in Python - Become a Python Ninja

Data Dependence

Copyright © 2023 · Monochrome Pro on Genesis Framework · WordPress · Log in

  • Home
  • Top Resources
  • Who Are You?