Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Python Dictionaries | Other Data Types in Python
Practice
Projects
Quizzes & Challenges
Quiz
Challenges
/
Introduction to Python (dev copy)

bookPython Dictionaries

Scorri per mostrare il menu

In previous chapters, we dove into data structures that rely on numeric indices. Now, we're going to explore a structure that uses a key — whether it's a string, tuple, number, and so on — to index its values. This structure is known as a dictionary. Within dictionaries, data is stored in key-value pairs. Here are some key points to remember about dictionary keys:

  • You can use any immutable type as a dictionary key;
  • Tuples can serve as keys, but only if they contain strings, numbers, or other tuples;
  • A single dictionary won't have duplicate keys;
  • In Python, dictionaries are enclosed within curly brackets {}.

To illustrate, let's say we want to capture data about countries. The dictionary could use country names as keys, with corresponding values (like area and population) saved as tuples.

12345
# Create dictionary countries_dict = {'USA': (9629091, 331002651), 'Canada': (9984670, 37742154), 'Germany': (357114, 83783942)} print(countries_dict)
copy

Got it? So, how do you retrieve a particular item from a dictionary? As touched upon earlier, you reference an item in a dictionary using its key. If the key is a string (as in our example), remember to wrap it in quotation marks. Just like with list or tuple indices, you'll place the key inside square brackets.

123456
# Dictionary countries_dict = {'USA': (9629091, 331002651), 'Canada': (9984670, 37742154), 'Germany': (357114, 83783942)} # Information about Canada print(countries_dict["Canada"])
copy

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 11

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 4. Capitolo 11
some-alt