How to add entries in a dictionary?

1

How do I add entries provided by a user in a dictionary? For example:

Entry:

1 abcde
2 adecd
3 aaabb

The created dictionary would be:

dicionario = {'abcde' : 1, 'adecd' : 2, 'aaabb' : 3}

or

dicionario = {1 : 'abcde', 2 : 'adecd', 3 : 'aaabb'}

Is there a function similar to append() to use in dicinarios as it is used in list? I say this because as the inputs will be provided by the user, you can not be adding input per input ( dicionario['abcde'] = 1 ).

    
asked by anonymous 17.04.2016 / 14:33

4 answers

2

You can use something like:

entrada1 = input("Por favor insira um numero: ")
dicionario[entrada1] = 1
    
17.04.2016 / 14:39
1

The most practical to attach a new index with a set value

dicionario['abcde'] = 1

But I do not understand what's stopping you from using it.

You commented:

  

I say this because as inputs will be provided by the user,   can be added by input (dictionary ['abcde'] =   1).

So another way of doing it would be with the update () method

dicionario.update({'abcde':1})

Getting the data via raw cgi

import cgi
form = cgi.FieldStorage()

for key in form:
    dicionario[key] = form[key]

Getting the data via request.POST

for key in request.POST:
    dicionario[key] = request.POST[key]
    
17.04.2016 / 14:40
1

For this example you are showing:

1 abcde  
2 adecd  
3 aaabb

As if the user entered the values  separated in this way you can do so:

user_input = input('1 abcde')# simulando a entrada do usuário  
user_input = user_input.split(' ')  
user_notes[user_input[0]] = user_input[1];
    
17.04.2016 / 15:02
0
d = {}
v = raw_input('valor: ')
d.update({len(d)+1:v})

Or put in a loop:

d = {}
while True:
    v = raw_input('valor')
    if v == 'Q':
        break
    d.update({len(d)+1:v})
print d
    
18.04.2016 / 14:51