Reputation: 1643
I have a dictionary in python which is of format
dict = {
'p_id': 254,
's_id': 1,
'object_cnt': 4,
'type0': 0,
'address0': 65500,
'size0': 2,
'value0': 23.4,
'type1': 1,
'address1': 65535,
'size1': 2,
'value1': 45.7,
'type2': 2,
'address2': 65,
'size2': 0,
'value2': 1,
'type3': 3,
'address3': 535,
'size3': 0,
'value3': 0,
}
Since the object_cnt is 4, there will four objects in this dictionary.
'type0': 0,
'address0': 65500,
'size0': 2,
'value0': 23.4,
The above can be considered as one object. I want to create a dictionary of form
new_dict = {
'65500' : (2,23.4)
'65535' : (2,45)
'65' : (0,1)
'535' : (0,0)
}
#address of a object as key and (size_object,value_object) as value
Can someone help me with this?
Thanks
Upvotes: 1
Views: 55
Reputation: 4189
a = {
'p_id': 254,
's_id': 1,
'object_cnt': 4,
'type0': 0,
'address0': 65500,
'size0': 2,
'value0': 23.4,
'type1': 1,
'address1': 65535,
'size1': 2,
'value1': 45.7,
'type2': 2,
'address2': 65,
'size2': 0,
'value2': 1,
'type3': 3,
'address3': 535,
'size3': 0,
'value3': 0,
}
n = a['object_cnt']
new_dict = dict()
for i in range(n):
new_dict[str(a['address{}'.format(i)])]=(a['size{}'.format(i)],a['value{}'.format(i)])
print(new_dict)
#{'65500': (2, 23.4), '65535': (2, 45.7), '65': (0, 1), '535': (0, 0)}
Upvotes: 1
Reputation: 29742
Use string formatting:
res = {d['address%s' % i]: [d['size%s' %i], d['value%s' % i]] for i in range(d['object_cnt'])}
Output:
{65: [0, 1], 535: [0, 0], 65500: [2, 23.4], 65535: [2, 45.7]}
Upvotes: 2