Question about appending items on a dictionary


#1

Hi guys. Here's my code:

def askbrand():
    a = input("Please enter brand: ")

def askprice():
    b = input("How much: ")

phonebrand={}
a=askbrand()
b=askprice()
phonebrand[a]=b

print(phonebrand)

How come when I print it out, it gives me {none:none}? I was kinda planning to have the inputs inserted into a dictionary. Any alternative way of doing this? Thanks in advance! :smile:


#2

You can try this

def askbrand():
    #for python3.x input("Please enter brand: ")
    return raw_input("Please enter brand: ")
    

def askprice():
    #for python3.x return input("How much: ")
    return raw_input("How much: ")

phonebrand={}
while(True):
    a = askbrand()
    b=askprice()
    if(a.lower() == "x" or b.lower()=="x"):
        break
    else:
        #using this method is really fast but will only allow for one one key-value entry
        # if there is multiple priced for the same inventory it will pick the first
        phonebrand.setdefault(a,[b])

print('The iventory is:\n')
print(phonebrand.items())

sample run results

or you can use this

def askbrand():
    #for python3.x raw_input("Please enter brand: ")
    return raw_input("Please enter brand: ")
    

def askprice():
    #for python3.x return input("How much: ")
    return raw_input("How much: ")

phonebrand={}
while(True):
    a = askbrand()
    b=askprice()
    if(a.lower() == "x" or b.lower()=="x"):
        break
    else:
        # to prevent that pitfall noted in version 1 you can use the code below
        phonebrand[a] = phonebrand.get(a,list())+[b]

print('The iventory is:\n')
print(phonebrand.items())

sample run results

or you can test it here

Click here to labs


#3

Wow @rydan ! You know if I can like your post 1 million times I surely would!!! Thank you sooo mucchh! :smile: