Python - update() failure to merge dictionaries

Asked

Viewed 79 times

-1

Hello I searched and found that dictionaryA.update(dictionaryB) is able to join the two dictionaries together. I tested and it actually works. But in the little exercise program below, it does not unite, but keeps only the last dictionary I keep. The part of the show that I show you looks complex, but it’s very simple, at my level. It’s a rap sheet for a football and goals player he played in a few games. In theory I would have a dictionary with several dictionary_player inserted in it, but I can only do this in a list (in the example named registered), but not in the dictionary (in the example named in_dict. Here’s the code:

# declaração de variáveis
gols = 0
marcou = 0
ficha = dict()
jogos = list()
gols = list()
jogo = ''
cadastrados = list()
in_dict = dict()
# cadastro de jogador
while True:
    part = 1
    #ficha.clear()
    ficha['nome'] = input('Nome: $: ')
    ficha['ano'] = int(input('Ano: $: '))
    ficha['time'] = input('Time: $: ')
    ficha['torneio'] = input('Torneio: $: ')
    ficha['jogadas'] = int(input('Partidas realizadas: $: '))
    print('Gols marcados por partida: ')
    while True: 
        jogos.append('jogo_'+str(part))
        gols.append(int(input('Gols: $ ')))
        part += 1
        sn = input('Novo jogo? [S/N] $ ').upper()
        if sn in 'Nn':
            break
# criação do dicionário
    ficha.update(zip(jogos, gols))
    # dicionário1.update(dicionário2) une os 2 dicionários
    # zip transforma duas listas em tuplas {key: valor} gerando um dicionário
    print('ficha_1', ficha) <--- PRINT DE CONTROLE
    jogos.clear()
    gols.clear()
    cadastrados.append(ficha.copy()) <--- AQUI A FICHA É ACRESCIDA A UMA LISTA E ok EM JUNTAR VÁRIOS DICIONÁRIOS NA LISTA
    in_dict.update(ficha) <--- AQUI APENAS O ÚLTIMO CADASTRO(FICHA) DO JOGADOR FICA NO DICIONÁRIO in_dict
    print('cadas', cadastrados, 'in_dict', in_dict) <--- PRINT DE CONTROLE
    sn = input('Novo cadastro? $ ').upper()
    if sn in 'Nn':
        break
print('ficha_2',ficha) <--- PRINT DE CONTROLE

resposta do terminal para um teste (para identificar onde são gerados ver PRINTS DE CONTROLE):
ficha_1 {'nome': 'b', 'ano': 2, 'time': 's', 'torneio': 's', 'jogadas': 2, 'jogo_1': 2, 'jogo_2': 3} (último cadastro criado)
cadas [{'nome': 'a', 'ano': 1, 'time': 's', 'torneio': 'r', 'jogadas': 2, 'jogo_1': 0, 'jogo_2': 1}, {'nome': 'b', 'ano': 2, 'time': 's', 'torneio': 's', 'jogadas': 2, 'jogo_1': 2, 'jogo_2': 3}] lista com os dois cadastros do teste
in_dict {'nome': 'b', 'ano': 2, 'time': 's', 'torneio': 's', 'jogadas': 2, 'jogo_1': 2, 'jogo_2': 3} dicionário apenas com o último cadastro

1 answer

2


Come on, first you have to understand how a dictionary works.

The dictionary has the following structure:

Dicionário[Chave] = valor

or can also be shown as follows:

Dicionário = {Chave: valor}

Keys in a Dictionary are unique, there’s no way to duplicate a key in a dictionary.

Briefly, if I make a dictionary with an X key and a Y value, and then use the same key with a Z value, it will overwrite the Y value that was inside the key, as it is not possible to create a key that you already have in the dictionary; just modify it or overwrite it.

From what I saw in your most recommended script is to create dictionaries within a dictionary, using the person’s name as indentification:

Example:

Dicionario['Antonio'] = {}  
Dicionario['Antonio']['jogo'] = valor
...

get going...

Dictionary serves exactly to facilitate the search, and if you are making a dictionary of users, what is the best way to search for them in the dictionary? using CPF, user name, user id in the database...

An example I use a lot at work is using dictionaries to divide users by state. Example:

# pegar todos e-mails de clientes de São Paulo
for i in dicionario['SP']
     i['e-mail']

But that’s it, good luck.

  • Thank you very much. Let me fool by the test I did with update. I created 3 dictionaries with the same name (a), but with different internal values, I didn’t realize it; so I did 3 times a.update(a) and OK, then I did initially plug.update(fiche) and then the example in_dict.update(fiche), always giving substitution. I did as you suggested and it worked OK.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.