Home > Software design >  How to make the dictionary.Item into a key for another dictionary and keep the new key also
How to make the dictionary.Item into a key for another dictionary and keep the new key also

Time:11-09

I have scenario A a dictionary that I would wish to transform using this method if it's possible or is there an alternative

A = {A:1,B:2,C:3}

B =  {values[1] : values[1]*2 for values in A.items()}

Desired outcome:

B = {1:2,2:4,3:6}

CodePudding user response:

How about:

A = (1,2,3)
B = {item:item*2 for item in A}

If you still want a dictionary A, could be:

A = {'A':1, 'B':2, 'C':3}
B = {item[1]:item[1]*2 for item in A.items()}

CodePudding user response:

B = {val:val*2 for val in A.values()}.

Ordered dicts are only ensured >= Python3.7 so while this will likely work in Python < 3.7 it would be bad practice not to use an OrderedDict or list. Also, items in the construct of dictionaries are a dict method yielding a dict_items class so is slightly misleading to use as an iterator variable name. In the future, SO appreciates using working code examples as your input does not (A:1 vs "A") etc. ;)

  • Related