osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

How to multiply dictionary values with other values based on the dictionary's key?


On Sun, 19 Aug 2018 03:35:24 -0700, giannis.dafnomilis wrote:

> On Sunday, August 19, 2018 at 3:53:39 AM UTC+2, Steven D'Aprano wrote:
[...]

>> If you know absolutely for sure that the key format is ALWAYS going to
>> be 'FEq_(<fields>)' then you can extract the fields using slicing, like
>> this:
>> 
>>   key = 'FEq_(0,_0,_2,_2)'
>>   fields = key[5, -1]  # cut from char 5 to 1 back from the end
[...]
>> - delete any underscores
>> - split it on commas
>> - convert each field to int
>> - convert the list of fields to a tuple
>> 
>>   fields = fields.replace('_', '')
>>   fields = string.split(',)
>>   fields = tuple([int(x) for x in fields])
>> 
>> 
>> and then you can use that tuple as the key for A.
> 
> When I try to this, I get the message 'fields = key[5, -1]. TypeError:
> string indices must be integers'.

Ouch! That was my fault, sorry, it was a typo. You need a colon, not a 
comma. Sorry about that!

Try this instead:

key = 'FEq_(0,_0,_2,_2)'
fields = key[5:-1]
fields = fields.replace('_', '')
fields = fields.split(',')
fields = tuple([int(x) for x in fields])
print(fields)


which this time I have tested.


(More comments later, time permitting.)


-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson