dict Python

We continue to explain the use of dict in Python through practical examples.

dict Python – first example

So let’s write a program that generates a dictionary of n elements that contains pairs of values ​​(i, i * i) and therefore values ​​of the type {1: 1, 2: 4, 3: 6,…}.

Let’s solve the algorithm very simply. We first ask how many elements the dictionary must have. Then, with a for loop, we generate the values.


n = int(input('How many items do you want to insert?: '))
d = dict()
for i in range(1, n+1):
    d[i] = i * i

print(d)

Let’s try the code directly in the online compiler below:

dict Python – second example

Let’s take a second example with Python dictionaries.

Given a dictionary of contacts, composed of pairs of values ​​Name: Telephone first print all the values ​​with the values​​() method on the dictionaries and then with a loop for print the telephones.

Here is a possible solution:


contacts = {
    'Tom': '2345610',
    'Anna': '12345610',
    'Luca': '32345610',
    'Harry': '42345610'
}

contacts_values = contacts.values()
print(valori)

for phone in contacts_values:
    print(phone)

We could also print the keys, using the keys() method on the dictionary and with a loop to print the names. Here is a possible solution to the variation to the proposed algorithm.


contacts = {
    'Tom': '2345610',
    'Anna': '12345610',
    'Luca': '32345610',
    'Harry': '42345610'
}

contacts_names = contacts.keys()
print(contacts_names)

for name contacts_names:
    print(name)

dict Python – third example

Let’s take a final example to get some more practice with dictionaries.

Extract 4 cards from a deck of 40 and put them into an initially empty dictionary, created with dict() in Python. The key is the seed, while the value is the number.

Here is a possible solution to the proposed algorithm (we will realize that it is an incorrect procedure and I will also explain why):


import random

def estract_cards():
  types = ["Bastoni", "Coppe", "Denari", "Spade"]
  numbers = ["Asso",'Due','Tre','Quattro','Cinque','Sei','Sette',"Fante","Cavallo","Re"]
  result = dict()
  
  for i in range(1,4):
    number = random.choice(numbers)
    type = random.choice(types)
    result[type] = number
  return result

r = estract_cards()
print(r)

If you try the algorithm several times, in the online compiler above, you will find that the dictionary is not always populated with 4 elements. Why does this happen?

As we know, in dictionaries the keys must be unique, this means that every time the algorithm extracts a key that has already been entered, it goes on with the count but does not enter anything.

So the correct and fastest solution is done with the while loop:


import random

def estract_cards():
  types = ["Bastoni", "Coppe", "Denari", "Spade"]
  numbers = ["Asso",'Due','Tre','Quattro','Cinque','Sei','Sette',"Fante","Cavallo","Re"]
  result = dict()
  print(len(result))
  
  while len(result) < 4:
    number = random.choice(numbers)
    type = random.choice(types)
    result[type] = number
  return result
  
r = estract_cards()
print(r)

If you try the while solution in the online compiler, this time the dictionary fills up with exactly 4 elements each time. In this case, in fact, I set a condition: as long as the dictionary does not have 4 elements, it continues to extract elements.

In this way we have solved the problem of duplicate keys to populate dictionaries in Python.

Conclusion

In this lesson we have dealt with some Python exercises on dict, in the next lessons I will propose many others.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *