Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary help
#1
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!
Reply
#2
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
You can also do the following
demonspawn = {
    'level': 1
}

demonspawn.update({
    'xpreward': round(demonspawn['level']*1.5),
    'str': round(demonspawn['level'] * 1.5)
})
Reply
#4
(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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020