I would like to build a dict in which one value is built from another.
I thought writing
d = {
'a':1,
'b':self['a']+1
}
but it did not work as expected :
>>> {'a':1, 'b':self['a']+1}
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'self' is not defined
So, how can I achieve that Python trick ? (I'm using Python 2.4
)
You can't reference a dictionary that has not yet been created. Just assign additional keys after creating the dictionary:
d = {'a': 1}
d['b'] = d['a'] + 1
Alternatively, set the value to a separate variable first , then create the dictionary:
a_value = 1
d = {'a': a_value, 'b': a_value + 1}
If you only have two values, calculate a first, then add b as a separate line.
If the dependencies are more complex, it may be worthwhile to use a function to provide values.
Python 2.7 onwards has dictionary comprehension:
mydict = {key: value for (key, value) in iterable}
Equivalent in earlier would be:
mydict = dict((key, value) for (key, value) in iterable)
Now you provide the iterable function for generating the values:
def get_dictionary_values():
a = get_really_expensive_calculation()
yield ('a', a)
b = a + modification_value
yield ('b', b)
# Add all other values here that calculate from earlier values.
mydict = dict((key, value) for (key, value) in get_dictionary_values())
With options of loops inside the function as needed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.