Python Forum

Full Version: Dictionary help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I'm trying to understand dictionaries better.
My problem is I'm trying to dynamically alter a value inside of a dictionary with a value inside that same dictionary.
demonspawn = {
        'level': 1,
        'xpreward': round(demonspawn['level']*1.5),
        'str': round(demonspawn['level'] * 1.5),
}
Error:
File "line 3, in <module> 'xpreward': round(demonspawn['level']*1.5), NameError: name 'demonspawn' is not defined
Error:
Using variable demonspawn before assignment
Can anybody help me resolve this issue while also achieving my goal?
Thank you!
demonspawn = {
        'level': 1,
}

demonspawn2 = {
        **demonspawn, 
        'xpreward': round(demonspawn['level']*1.5),
        'str': round(demonspawn['level'] * 1.5),
}
Your approach does not work, because you try to access a dictionary before it's assigned. This could not work.
You can make a second dict and add also the content from the first dict. I think this nice change was released with Python 3.5.

You you can unpack arguments and unpack keyword arguments.
You can also do the following
demonspawn = {
    'level': 1
}

demonspawn.update({
    'xpreward': round(demonspawn['level']*1.5),
    'str': round(demonspawn['level'] * 1.5)
})
(Jul-29-2019, 09:31 AM)SheeppOSU Wrote: [ -> ]You can also do the following
demonspawn = {
    'level': 1
}

demonspawn.update({
    'xpreward': round(demonspawn['level']*1.5),
    'str': round(demonspawn['level'] * 1.5)
})

This is exactly what I needed, Thank you.