Skip to content
Home » Dictionary Methods – fromkeys

Dictionary Methods – fromkeys

Spread the love

In some of my previous articles we discussed the following dictionary methods:

pop and popitem

get

setdefault

Feel free to read about them if you haven’t done so yet.

In this article we’ll be talking about another dictionary method, fromkeys.

Here’s the video version of this article:

The fromkeys(sequence[, value]) method creates a new dictionary with keys from sequence. If the optional parameter value is given, all the values are set to it. Here we’re using a list as the sequence:

 >>> sequence = ["first name", "last name", "address"] 

If the value parameter is not passed to the method, the values default to None:

 >>> data_dictionary = dict.fromkeys(sequence)
 >>> data_dictionary
 {'first name': None, 'last name': None, 'address': None} 

So let’s try setting the value in the method:

 >>> data_dictionary = dict.fromkeys(sequence, "Top secret")
 >>> data_dictionary
 {'first name': 'Top secret', 'last name': 'Top secret', 'address': 'Top secret'} 

Here’s how it looks with tuples:

 >>> sequence = ("first name", "last name", "address")
 >>> data_dictionary = dict.fromkeys(sequence, "Unknown")
 >>> data_dictionary
 {'first name': 'Unknown', 'last name': 'Unknown', 'address': 'Unknown'} 

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Also strings and ranges can be used:

 >>> sequence = "ABC"
 >>> data_dictionary = dict.fromkeys(sequence, "?")
 >>> data_dictionary
 {'A': '?', 'B': '?', 'C': '?'}
  
 >>> sequence = range(4)
 >>> data_dictionary = dict.fromkeys(sequence, 0)
 >>> data_dictionary
 {0: 0, 1: 0, 2: 0, 3: 0}  

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply