I try to create a dictonary with Python 3. Here is my code:
data = {}
data['price'] = []
data['place1'] = []
data['place2'] = []
data['place1'].append({
'x': 2,
'y': 1
})
data['place2'].append({
'a': 5,
'b': 6
})
data['price'].append(data['place1'])
data['price'].append(data['place2'])
print(data)
so the output ist:
{'price': [[{'x': 2, 'y': 1}], [{'a': 5, 'b': 6}]], 'place1': [{'x': 2, 'y': 1}], 'place2': [{'a': 5, 'b': 6}]}
But I need it like in this example:
'price'
->'place1'
->'x'=2
->'y'=1
->'place2'
->'a'=5
->'b'=6
Is diconary the correct method for this?
Thanks for your help, Best, Marius
Well, you're appending lists here: data['price'].append(data['place1'])
, so now data['price']
is a list of lists.
You can write a simple dictionary literal instead:
data = {
'price': {
'place1': {
'x': 2,
'y': 1
},
'place2': {
'a': 5,
'b': 6
}
}
}
Or, if you insist on appending data dynamically:
data = {'price': {}}
data['price']['place1'] = {'x': 2, 'y': 1}
data['price']['place2'] = {'a': 5, 'b': b}
Just to keep the original content as much as possible, you need to make data['price']
a dict then put place1
and place2
inside it.
data = {}
data['price'] = {}
data['price']['place1'] = []
data['price']['place2'] = []
data['price']['place1'].append({
'x': 2,
'y': 1
})
data['price']['place2'].append({
'a': 5,
'b': 6
})
No, you cannot map the (:) on the dictionary to an (=) sign as your output.
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.