Home > Software engineering >  Re-defining a dict key value
Re-defining a dict key value

Time:07-29

This code doesn't work - is there another way I can add a key-value pair with a variable as the value?

BTC_ = {"Name": "BTC", "liq": 57000}
ETH_ = {"Name": "ETH", "liq": 50000}

BTC = BTC_['liq']
ETH = ETH_['liq']

ETHp = ETH / 50000
BTCp = BTC / 50000

BTC_.update['price': BTCp ]
ETH_.update['price': ETHp ]

This code currently gives the error:

Output: builtin_function_or_method object is not subscriptable 

CodePudding user response:

You call functions with (arguments) after the function name, not [arguments]. And the argument to dict.update() must be a dictionary or key=value named arguments. So the correct syntax would be:

BTC_.update({'price': BTCp})
# or
BTC_.update(price=BTCp)

But if you're just setting one element, this is normally done using assignment:

BTC_['price'] = BTCp

.update() is normally only used when you want to set multiple elements, often by merging with another dictionary.

CodePudding user response:

Change [] to () and enclose the argument in {} (thus turning it into a dictionary):

BTC_ = {"Name": "BTC", "liq": 57000}
ETH_ = {"Name": "ETH", "liq": 50000}

BTC = BTC_['liq']
ETH = ETH_['liq']

ETHp = ETH / 50000
BTCp = BTC / 50000

BTC_.update({'price': BTCp})
ETH_.update({'price': ETHp})

print(BTC_)
print(ETH_)
  • Related