Reputation: 198
I'm trying to create a dict()ionary of random unique keys and the value to be a class object or whatever.
The problem is that when I cycle through the dictionary using FOR IN all I'm given is the key name when what I really want is a reference to a dictionary item.
Let me explain in code:
a = dict()
a['trees'] = dict()
a['trees']['oak'] = 453
a['trees']['pine'] = 12
a['trees']['chestnut'] = 65
for b in a['trees']:
print b
The output is:
oak pine chestnut
what I want is:
{'oak' : 453} {'pine' : 12} {'chestnut' : 65}
I've tried:
FOR b in a['trees'].items():
But that returns tuples with copied data meaning I can't change a value and effect the original item in the dictionary.
I could do this:
FOR b in a['trees']:
tree = a['trees'][b]
But that seems a bit long winded and I sure it can be done within the FOR statement.
I sure I'm missing something pretty simple here :/ thanks for your comments in advance guys.
Upvotes: 0
Views: 112
Reputation: 399
here your answer
a = dict()
a['trees'] = dict()
a['trees']['oak'] = 453
a['trees']['pine'] = 12
a['trees']['chestnut'] = 65
for b in a:
if a.get("trees"):
print a.items()
It's possible to create lists from dictionaries by using the methods items(), keys() and values(). As the name implies the method keys() creates a list, which consists solely of the keys of the dictionary. While values() produces a list consisting of the values. items() can be used to create a list consisting of 2-tuples of (key,value)-pairs:
>>> w={"house":"Haus","cat":"Katze","red":"rot"}
>>> w.items()
[('house', 'Haus'), ('red', 'rot'), ('cat', 'Katze')]
>>> w.keys()
['house', 'red', 'cat']
>>> w.values()
['Haus', 'rot', 'Katze']
If we apply the method items() to a dictionary, we have no information loss, i.e. it is possible to recreate the original dictionary from the list created by items(). Even though this list of 2-tuples has the same entropy, i.e. the information content is the same, the efficiency of both approaches is completely different. The dictionary data type provides highly efficient methods to access, delete and change elements of the dictionary, while in the case of lists these functions have to be implemented by the programmer.
Upvotes: -1
Reputation: 90909
From the question , the main point seems to be -
But that returns tuples with copied data meaning I can't change a value and effect the original item in the dictionary.
As you observed, when you iterate over a dictionary you get the keys, not sub dictionaries (or key/value pairs).
You can use dict.iteritems()
and then unpack the value into key and value , and then use that to make changes to your original dictionary. Example -
>>> d = {1:2,3:4,5:6}
>>> for key,value in d.iteritems():
... d[key] = value + 1
...
>>> d
{1: 3, 3: 5, 5: 7}
Also, if accessing a['trees'][b]
looks long to you, you can assign the reference to a['trees']
dictionary to a shorter variable and use that for your needs. Example -
>>> a = dict()
>>> a['trees'] = dict()
>>> a['trees']['oak'] = 453
>>> a['trees']['pine'] = 12
>>> a['trees']['chestnut'] = 65
>>> b = a['trees']
>>> for key,value in b.iteritems():
... b[key] = value + 100
...
>>> a
{'trees': {'chestnut': 165, 'oak': 553, 'pine': 112}}
Upvotes: 2
Reputation: 25528
I'm not sure exactly what you want, but the get a list of dictionaries from a
, you can use:
In [14]: [dict((x,)) for x in a['trees'].items()]
Out[14]: [{'chestnut': 65}, {'oak': 453}, {'pine': 12}]
To get a string matching your expected output, try:
In [15]: print ' '.join([str(dict((x,))) for x in a['trees'].items()])
{'chestnut': 65} {'oak': 453} {'pine': 12}
Upvotes: 0
Reputation:
for b in a['trees']:
print '{\'' + b + '\':' + str(a['trees'][b]) + '}'
output:
{'chestnut':65}
{'oak':453}
{'pine':12}
Upvotes: 0