Reputation: 75
Beginner programmer here. I have 2 questions.
Turn a list into a nested dictionary:
house_prices = ['£200k', '£300k', '£500k'`]
I want to turn it into--
House_price_dict = {
'house1': {'price':'£200k'},
'house2': {'price':'£300k'},
'house3': {'price:'£500k'},
}
Turn two lists into a nested dictionary:
house_prices = ['£200k', '£300k', '£500k'`]
no_of_bedrooms = [2, 3, 5]
I want to turn into--
house_info_dict = {
'house1': {
'price':'£200k',
'no_of_bedrooms':2,
},
'house2': {
'price':'£300k',
'no_of_bedrooms': 3,
},
'house3': {
'price:'£500k',
'no_of_bedrooms': 5,
},
}
Upvotes: 2
Views: 101
Reputation: 325
d = {}
for i in xrange(len(house_prices)):
d["house{}".format(i+1)] = { "price": house_prices[i] }
For the second part:
d = {}
for i in xrange(len(house_prices)):
d["house{}".format(i+1)] = { "price": house_prices[i], 'no_of_bedrooms': no_of_bedrooms[i] }
Note that house_prices
and no_of_bedrooms
must be in the same size, otherwise IndexError
will be raised.
Upvotes: 2
Reputation: 10544
We can use dictionany comprehension
house_prices = ['£200k', '£300k', '£500k']
House_price_dict = {f'house{idx}':{'price':i} for idx, i in enumerate(house_prices, start=1)}
#{'house1': {'price': '£200k'},
# 'house2': {'price': '£300k'},
# 'house3': {'price': '£500k'}}
no_of_bedrooms = [2, 3, 5]
house_info_dict = {f'house{idx}':{'price':i[0], 'no_of_bedrooms': i[1]} for idx, i in enumerate(zip(house_prices, no_of_bedrooms), start=1)}
#{'house1': {'price': '£200k', 'no_of_bedrooms': 2},
# 'house2': {'price': '£300k', 'no_of_bedrooms': 3},
# 'house3': {'price': '£500k', 'no_of_bedrooms': 5}}
Upvotes: 0
Reputation: 27311
The zip function takes multiple lists and returns tuples with one element from each list:
>>> house_prices = ['200k', '300k', '500k']
>>> no_of_bedrooms = [2, 3, 5]
>>>
>>> list(zip(house_prices, no_of_bedrooms))
[('200k', 2), ('300k', 3), ('500k', 5)]
>>>
zip returns a generator, so I convert it to list above to see the result.
There is a built-in enumerate function that returns both the index and the value in a list:
>>> for i, n in enumerate(['a', 'b', 'c'], start=1):
... print(i, n)
...
1 a
2 b
3 c
>>>
combining the two, gives:
>>> list(enumerate(zip(house_prices, no_of_bedrooms), start=1))
[(1, ('200k', 2)), (2, ('300k', 3)), (3, ('500k', 5))]
and you can feed this into a dict comprehension:
>>> house_info_dict = {'house%d' % i: {
... 'price': p,
... 'no_of_bedrooms': n
... } for i, (p, n) in enumerate(zip(house_prices, no_of_bedrooms), start=1)}
>>> house_info_dict
{'house3': {'no_of_bedrooms': 5, 'price': '500k'}, 'house2': {'no_of_bedrooms': 3, 'price': '300k'}, 'house1': {'no_of_bedrooms': 2, 'price': '200k'}}
a trick to print it in a prettier format is to use the json module:
>>> import json
>>> print(json.dumps(house_info_dict, indent=4))
{
"house3": {
"no_of_bedrooms": 5,
"price": "500k"
},
"house2": {
"no_of_bedrooms": 3,
"price": "300k"
},
"house1": {
"no_of_bedrooms": 2,
"price": "200k"
}
}
>>>
Upvotes: 3