Dictionaries in Python

Dictionaries in Python

Being familiar with data structures that help organize and manipulate data efficiently is essential when working with programming languages. One such data structure is the dictionary, a powerful tool for storing and retrieving data in Python.

When choosing a collection type, it is useful to understand its properties. Choosing the right type for a particular data set could mean retention of meaning and increased efficiency or security.

In this blog post, we will explore the concept of dictionaries in Python in the easiest way possible, accompanied by examples to illustrate their usage.

What is a Dictionary?

Dictionaries are used to store data values in key: value pairs. A dictionary is a collection that is ordered*, changeable, and does not allow duplicates. The values in dictionary items can be of any data type. Dictionaries are written with curly brackets {} and have keys and values:

NOTE: In this article, the same example is used throughout to perform different coding functions. Please use this example to print the result in your python editor.

  1. Creating a Dictionary:

Example : Create and print a dictionary:

thisdict = {"brand":"Ford",
            "model":"Mustang",
            "year": 1994,
}
print(thisdict)

OUTPUT:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1994}        

2. Dictionary Items:

Dictionary items are presented in key: value pairs and can be referred to by using the key name.

Example: Print the "brand" value of the dictionary:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1994
}
print(thisdict["brand"]
OUTPUT: Ford        

3. Accessing Items: You can access the items of a dictionary by referring to its key name, inside square brackets:

get( ) Method : There is also a method called get( ) that will give you the same result.

Example: Using the previous example, Get the value of the "model" key:

x = thisdict["model"] 
print(x) 
OUTPUT: Mustang 

x = thisdict.get("model") 
print(x) 
OUTPUT: Mustang        

4. The dict( ) Constructor : It is also possible to use the dict() constructor to make a dictionary.

Example : Using the dict( ) method to make a dictionary:

thisdict = dict(name = "John", age = 36, country = "Norway") print(thisdict)

OUTPUT: {'name': 'John', 'age': 36, 'country': 'Norway'}        

Dictionary Methods

Dictionary len( ): To determine how many items a dictionary has, use the len( ) function.

Dictionary data type( ): From Python's perspective, dictionaries are defined as objects with the data type 'dict':

Using the above example, find the length and data type of the dictionary:

print(len(thisdict))
print(type(thisdict))

OUTPUT:
3
<class 'dict'>        

keys( ) Method: The keys( ) method will return a list of all the keys in the dictionary.

values( ) Method: The values( ) method will also return a list of all the values in the dictionary.

Example: Using the previous example, Get the keys and value of the dictionary:

x = thisdict.keys()
print(x)
OUTPUT: dict_keys(['brand', 'model', 'year'])

x = thisdict.values()
print(x)
OUTPUT: dict_values(['Ford', 'Mustang', 1994])        

Adding Items: Adding an item to the dictionary is done by using a new index key and assigning a value to it:

Example: Using the above example, Add a new item to the original dictionary, and see that the keys list gets updated as well

thisdict["color"] = "red"
print(thisdict)

OUTPUT: {'brand': 'Ford', 'model': 'Mustang', 'year': 1994, 'color': 'red'}         

Items( ) Method: The items() method will return each item in a dictionary as tuples in a list.

x = thisdict.items()
print(x)
OUTPUT:  dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1994)])        

Check if Key Exists: To determine if a specified key is present in a dictionary use the 'in' keyword:

if "model" in thisdict:
    print("Yes, 'model' is one of the keys in thisdict dictionary.")

OUTPUT: Yes, 'model' is one of the keys in thisdict dictionary.        

Change Values : You can change the value of a specific item by referring to its key name:

thisdict["year"] = 2001
print(thisdict)
OUTPUT: {'brand': 'Ford', 'model': 'Mustang', 'year': 2001}        

Update ( ) Method: The update() method will update the dictionary with the items from the given argument. The argument must be a dictionary, or an iterable object with key:value pairs.

thisdict.update({"year": 2002})
print(thisdict)
OUTPUT: {'brand': 'Ford', 'model': 'Mustang', 'year': 2002}

thisdict.update({"color": "White"})
print(thisdict)
OUTPUT: {'brand': 'Ford', 'model': 'Mustang', 'year': 2002, 'color': 'White'}        

Removing Items: There are several methods to remove items from a dictionary:

The pop() method: removes the item with the specified key name:

thisdict.pop("model")
print(thisdict)
OUTPUT: {'brand': 'Ford', 'year': 1994}        

The popitem() method: removes the last inserted item (in versions before 3.7, a random item is removed instead):

thisdict.popitem()
print(thisdict)
OUTPUT: {'brand': 'Ford', 'model': 'Mustang'}        

The del keyword: removes the item with the specified key name:

The del keyword can also delete the dictionary completely:

del thisdict["model"]
print(thisdict)
OUTPUT: {'brand': 'Ford', 'year': 1994}

del thisdict
print(thisdict) 
OUTPUT: #this will cause an error because "thisdict" no longer exists.        

Loop Dictionaries

For Loop: You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

Example: Print all the keys in the dictionary:

for x in thisdict:
    print(x)
OUTPUT:
brand
model
year        

Example: Print all values in the dictionary, one by one:

for x in thisdict:
    print(thisdict[x])
OUTPUT: 
Ford
Mustang
1994        

Values( ) Method: You can also use the values() method to return values of a dictionary:

Keys( ) Method: You can use the keys() method to return the keys of a dictionary:

for x in thisdict.keys():
  print(x)

for x in thisdict.values():
  print(x)        

Loop through both keys and values, by using the items() method:

for x, y in thisdict.items(): ?
print(x, y)

OUTPUT: 
brand Ford
model Mustang
year 2002        

Copy a Dictionary:

copy( ) Method: There are ways to make a copy, one way is to use the built-in Dictionary method copy().

Example : Make a copy of a dictionary with the copy( ) method:

mydict = thisdict.copy()
print(mydict)

OUTPUT: {'brand': 'Ford', 'model': 'Mustang', 'year': 1994}        

dict () Method: Another way to make a copy is to use the built-in function dict().

mydict = dict(thisdict)
print(mydict)
OUTPUT: {'brand': 'Ford', 'model': 'Mustang', 'year': 1994}        

Nested Dictionaries:

A dictionary can contain dictionaries, this is called nested dictionaries.

Example: Create a dictionary that contain three dictionaries:

myfamily = {
    "child1": {
    "name":"Emily",
    "year": 2004
},
    "child2" : {
    "name":"Betty",
        "year": 2006
    },
    "child3": {
    "name" : "Susie",
    "year": 2008
 }
}
print(myfamily)
print(type(myfamily))

OUTPUT: {'child1': {'name': 'Emily', 'year': 2004}, 'child2': {'name': 'Betty', 'year': 2006}, 'child3': {'name': 'Susie', 'year': 2008}}
<class 'dict'>        

To Add Dictionaries into one: Or, if you want to add three dictionaries into a new dictionary:

Example: Create three dictionaries, then create one dictionary that will contain the other three dictionaries:

child1 = {
    "name":"Emily",
    "year": 2004
}
child2 = {
    "name":"Betty",
    "year": 2006
}
child3 = {
    "name" : "Susie",
    "year": 2008
}
myfamily1 = {
    "child1": child1,
    "child2": child2,
    "child3": child3,
}
print(myfamily)
OUTPUT: {'child1': {'name': 'Emily', 'year': 2004}, 'child2': {'name': 'Betty', 'year': 2006}, 'child3': {'name': 'Susie', 'year': 2008}}        

Access Items in Nested Dictionaries: To access items from a nested dictionary, you use the name of the dictionaries, starting with the outer dictionary:

Example : Print the name of child 2:

print(myfamily["child2"]["name"])
OUTPUT: Emily        

SUMMARY OF ALL DICTIONARY METHODS:

clear():?Removes all the elements from the dictionary

copy(): Returns a copy of the dictionary

fromkeys(): Returns a dictionary with the specified keys and value

get(): Returns the value of the specified key

items(): Returns a list containing a tuple for each key value pair

keys(): Returns a list containing the dictionary's keys

pop(): Removes the element with the specified key

popitem(): Removes the last inserted key-value pair

setdefault(): Returns the value of the specified key. If the key does not exist: insert the key, with the specified value

update(): Updates the dictionary with the specified key-valuepairs

values(): Returns a list of all the values in the dictionary

Conclusion:

In closing, this article has covered the all the methods of dictionaries in Python, aimed at helping beginners in their Python learning journey. I plan to continue documenting my progress with various Python topics, hoping it will benefit other newcomers. Thank you for reading, and stay tuned for the next article. Here's to joyful learning ahead!

?

要查看或添加评论,请登录

社区洞察

其他会员也浏览了