How to Get First Key Value in a Dictionary

3.5/5 - (11 votes)

Problem Formulation and Solution Overview

In this article, you’ll learn how to get the first Key and Value from a key:value pair in a Python Dictionary.

A Dictionary in Python is used to store information in a key:value pair format. These pairs are modifiable and do not allow duplicates.

πŸ’‘ Note: In theory, the dictionary data type doesn’t provide any guarantee of ordering. In other words, there should be no such thing as getting the “first value” of a dictionary. If your application relies on the ordering of dictionary elements, I’d recommend using the OrderedDict type. In practice, however, things are different because dictionaries, in fact, keep the elements ordered in the cPython implementation of the Python specification. You cannot rely on it, though.

To make it more fun, we have the following running scenario:

Noah has decided to take his family on a fun getaway. He has a list of five (5) possible choices. After much ado, a vote was taken, and the first location was selected as the winner. Where is the family going (Key)? What are they staying in (Value)?


πŸ’¬ Question: How would we write code to get the first key:value pair in a Python Dictionary?

We can accomplish this task by one of the following options:


Method 1: Use dict.items()

This method uses dict.items() to access and retrieve the first key:value pair in a Dictionary.

getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo',  'Sweden': 'Treehouse', 'US': 'Lighthouse'}
winner = list(getaways.items())
print(winner)

Above, declares four (4) possible getaways, with the Dictionary Key indicating the location and the Value indicating the accommodations. These save to getaways.

The following line converts getaways (list(getaways.items()) to a List and returns a List of Tuples as shown below.

[('Switzerland', 'Windmill'), ('Canada', 'Igloo'), ('Sweden', 'Treehouse'), ('US', 'Lighthouse')]

To access the first key:value pair, slicing was used to access the Tuple.

winner = list(getaways.items())[0]
print(winner)
('Switzerland', 'Windmill')

To access the Key and Value individually, slicing was used once again.

winner = list(getaways.items())[0][0]
print(winner)

winner = list(getaways.items())[0][1]
print(winner)
Switzerland
Windmill
Python dict.items() Method

Method 2: Use dict.keys() and dict.values()

This method uses dict.keys() and dict.values() to access and retrieve the first key:value pair in a Dictionary.

getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo',  'Sweden': 'Treehouse', 'US': 'Lighthouse'}
first_key = list(getaways.keys())[0]
first_val = list(getaways.values())[0]
print(f'Noah and his family are going to {first_key} and staying in a {first_val}.')

Above, declares four (4) possible getaways, with the Dictionary Key indicating the location and the Value indicating the accommodations. These save to getaways.

The following two (2) lines access the first Key and the first Value using slicing. These save respectively to first_key and first_val.

Next, a formatted string is output to the terminal.

Noah and his family are going to Switzerland and staying in a Windmill.
Python dict.keys() Method

Method 3: Use next()

For this method, only the Value of the first key:value pair, is retrieved.

getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo',  'Sweden': 'Treehouse', 'US': 'Lighthouse'}
all_vals = getaways.values()
val_iter = iter(all_vals)
first_val = next(val_iter)
print(f'Noah and his family are staying in a {first_val}. The location is a secret!')

Above, declares four (4) possible getaways, with the Dictionary Key indicating the location and the Value indicating the accommodations. These save to getaways.

The following three (3) lines retrieve all the Dictionary Values, convert them to an object, retrieve the first Value and output a formatted string to the terminal.

Noah and his family are staying in a Windmill. The location is a secret!
Python Dictionary values() Method

Method 3: Use a For Loop and dict.items()

This method uses a for Loop and dict.items() to output the first key:value pair in a Dictionary.

getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo',  'Sweden': 'Treehouse', 'US': 'Lighthouse'}
for k, v in getaways.items():
  print(k, v)
  exit()

Above, declares four (4) possible getaways, with the Dictionary Key indicating the location and the Value indicating the accommodations. These save to getaways.

The next line instantiates a For loop to iterate through the Dictionary items.

Then, the first Key and Value are output to the terminal, and the loop terminates.

Switzerland Windmill

Method 5: Use Dictionary Comprehension

Dictionary Comprehension! A simplistic approach!

getaways = {'Switzerland': 'Windmill', 'Canada': 'Igloo',  'Sweden': 'Treehouse', 'US': 'Lighthouse'}
winner = {k: getaways[k] for k in list(getaways)[:1]}
print(winner)

Above, declares four (4) possible getaways, with the Dictionary Key indicating the location and the Value indicating the accommodations. These save to getaways.

Next, Dictionary Comprehension is used in conjunction with slicing to retrieve only the first Key and Value in the Dictionary and output the same to the terminal. Perfect!

{'Switzerland': 'Windmill'}
Python Dictionary Comprehension - A Powerful One-Liner Tutorial

✨A Finxter Favorite!
Simple! Yet Elegant!


Summary

These five (5) methods of retrieving the first Key and Value pair of a Dictionary should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!


Programmer Humor – Blockchain

“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source xkcd