Home > other >  change dictionary key of dictionary by index
change dictionary key of dictionary by index

Time:03-06

I have a dictionary dico that i created it with this code :

dico = {}
for index, row in data.iterrows():
    
    tup = (row['OsId'], row['BrowserId'])
    
   
    if tup not in dico:
        dico[tup] = []
    dico[tup].append(row['PageId'])
[print(f"{key} : {value}") for key, value in dico.items()]

here a sample of dico :

 combination : list of pages :

(99, 14) : [789615, 1158132, 789615, 789615, 1109643, 789615, 1184903]
(33, 16) : [955761, 955764, 955767, 955761, 955764, 955764, 1154705, 955761]
(12, 99) : [1068379, 1184903, 955764, 955761, 1184903, 955764]
(11, 99) : [1187774]

I am looking for a way to change the dico to replace the combination value by it's index in the list of combinations

For example i have the list of combination : (99, 14), (33, 16), (12, 99), (11, 99)

The expected result should be :

0 : [789615, 1158132, 789615, 789615, 1109643, 789615, 1184903]
1 : [955761, 955764, 955767, 955761, 955764, 955764, 1154705, 955761]
2 : [1068379, 1184903, 955764, 955761, 1184903, 955764]
3 : [1187774]

Any idea please to do it? thanks

CodePudding user response:

With a list of keys key_list = [(99, 14), (33, 16), (12, 99), (11, 99)]:

dict(enumerate(dico[k] for k in key_list))

CodePudding user response:

Is this what you want:

{i: value for i, value in enumerate(dico.values())}

CodePudding user response:

You cannot rename keys. You can iterate the list of keys (not directly) and insert the value of key old under another key and delete the old one:

keys = (99, 14), (33, 16), (12, 99), (11, 99)

d = {}
# iterates the LIST of keys, not dict.keys - that would not work
for idx, k in enumerate(keys,1):
    d[k] = 1111*idx

# before
print(d)

for idx,old in enumerate(keys):
    d[idx] = d[old]    # copy value
    del d[old]         # delete old key from dict

# after
print(d)

Output before:

{(99, 14): 1111, 
 (33, 16): 2222, 
 (12, 99): 3333, 
 (11, 99): 4444}

Output after:

{0: 1111, 
 1: 2222, 
 2: 3333, 
 3: 4444}

Or you create a fully new dict from it.

CodePudding user response:

This is a possible solution:

dico = dict(zip(range(len(dico)), dico.values()))

However, keep in mind that you're creating a new dictionary from scratch.

CodePudding user response:

The simplest solution is:

dico = dict(enumerate(dico.values()))

enumerate(dico.values()) gives you the equivalent of zip(range(len(dico)), dico.values()). Passing that sequence of tuples to dict() creates a new dictionary that uses the first element of each tuple as the key and the second element as the value.

  • Related