Python3 Data Type - Dict

1. Introduction

A dictionary, also known as dict, is a built-in Python data type that represents a collection of key-value pairs. It is one of the most commonly used data types in Python programming due to its versatility and efficiency in storing and retrieving data. In this article, we will explore the various aspects of dictionaries in Python 3.

2. Creating a Dictionary

To create a dictionary in Python, you can use the curly braces {} or the built-in dict() function. Each key-value pair is separated by a colon (:), and multiple pairs are separated by a comma (,). Here's an example:

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

print(my_dict)

This code creates a dictionary named my_dict with three key-value pairs: 'name' with value 'John', 'age' with value 25, and 'city' with value 'New York'. The output of the print statement will be:

{'name': 'John', 'age': 25, 'city': 'New York'}

2.1 Accessing Dictionary Values

To access the values in a dictionary, you can use square brackets [] and the key name. Here's an example:

print(my_dict['name'])

print(my_dict['age'])

print(my_dict['city'])

The above code will print:

John

25

New York

3. Modifying Dictionary Values

You can modify the values in a dictionary by assigning a new value to a specific key. Here's an example:

my_dict['age'] = 30

print(my_dict)

The output will be:

{'name': 'John', 'age': 30, 'city': 'New York'}

4. Dictionary Methods

4.1 keys() Method

The keys() method returns a list of all the keys in a dictionary. Here's an example:

print(my_dict.keys())

The output will be:

['name', 'age', 'city']

You can also use the list() function to convert the result into a list explicitly:

print(list(my_dict.keys()))

4.2 values() Method

The values() method returns a list of all the values in a dictionary. Here's an example:

print(my_dict.values())

The output will be:

['John', 30, 'New York']

4.3 items() Method

The items() method returns a list of all the key-value pairs in a dictionary, where each pair is represented as a tuple. Here's an example:

print(my_dict.items())

The output will be:

[('name', 'John'), ('age', 30), ('city', 'New York')]

5. Dictionary Length

The length of a dictionary, i.e., the number of key-value pairs it contains, can be obtained using the len() function. Here's an example:

print(len(my_dict))

The output will be:

3

6. Conclusion

In this article, we have explored the basics of dictionaries in Python 3. We learned how to create a dictionary, access its values, modify its values, and use some of the handy methods provided. Dictionaries are incredibly useful for organizing and manipulating data in Python, and they should be part of every programmer's toolkit.

免责声明:本文来自互联网,本站所有信息(包括但不限于文字、视频、音频、数据及图表),不保证该信息的准确性、真实性、完整性、有效性、及时性、原创性等,版权归属于原作者,如无意侵犯媒体或个人知识产权,请来电或致函告之,本站将在第一时间处理。猿码集站发布此文目的在于促进信息交流,此文观点与本站立场无关,不承担任何责任。

后端开发标签