Cooper2479
Cooper2479

Reputation: 3

Using the same key in two dictionaries (Python)

Here's what I have:

from pprint import pprint

Names = {}
Prices = {}
Exposure = {}

def AddName():
    company_name = input("Please enter company name: ")
    return company_name

def AddSymbol(company_name):
    stock_symbol = input("Please enter a stock symbol: ")
    Names[stock_symbol] = company_name
    return Names

^^ this updates the Names dictionary fine as {symbol:company name}

def AddPrices(stock_symbol):
    buy = float(input("Please enter buying price of stock: "))
    sell = float(input("Please enter current price of stock: "))
    Prices[stock_symbol] = buy, sell
    return Prices

^^ this generates a TypeError: unhashable type: 'dict' - what I want is it to update the Prices dictionary like {symbol: buy price, sell price, symbol2: buy price, sell price etc..}

def printDicts(Names, Prices):
    '''
    For debug purposes, prints out contents of dictionaries
    '''
    print( "Names is now:" )
    pprint(Names)

    print("Prices now:")
    pprint(Prices)



def main():
    company_name = AddName()
    stock_symbol = AddSymbol(company_name)
    AddPrices(stock_symbol)
    printDicts(Names, Prices)

main()

Being new to programming I'm not entirely sure how to fix this. Thanks for any help!

Upvotes: 0

Views: 71

Answers (3)

Eugene
Eugene

Reputation: 161

Perhaps what you meant to return in your AddSymbol function is the symbol and not another dictionary? In that case you do:

def AddSymbol(company_name):
    stock_symbol = input("Please enter a stock symbol: ")
    Names[stock_symbol] = company_name
    return stock_symbol

Upvotes: 0

SimonT
SimonT

Reputation: 2359

In AddSymbol(company_name) you return the entire Names dictionary. This entire dictionary is then passed into the AddPrices function. AddPrices is meant to have a stock symbol passed into it (a str) but you're passing a dict. You could modify AddSymbol to return stock_symbol instead of Names.

I would also recommend that your function names be camel-cased, beginning with a lowercase letter and capitalizing the first letter of each word. This is what most programmers do for consistency and it's good to form good habits.

Upvotes: 1

kriomant
kriomant

Reputation: 2326

Your AddSymbol returns Names, which is dictionary. Dictionary can't be used as dictionary key.

Just use return stock_symbol in AddSymbol.

Upvotes: 1

Related Questions