0

I will try to easily explain my problem. I have a dictionary that looks like this:

dic = {
   'I2a1a': ['I2a1a2', 'I2a1a2a', 'I2a1a2a1a2'],
   'I2a1b': ['I2a1b1a1a1b1a'],
   'I2a1b2': ['I2a1b2a']
}

Based on this dictionary, when the length of the value is > 1 I want to create a new dictionary that will look like this:

new_dic = {
   'I2a1a': 'I2a1a2', 'I2a1a2': 'I2a1a2a', 'I2a1a2a': 'I2a1a2a1a2',
   'I2a1b': 'I2a1b1a1a1b1a',
   'I2a1b2': 'I2a1b2a'
}

As we can see for the key 'I2a1a' in the first dictionary, each value (except the last value) is a key in the new_dic and the value associated with it is the index n+1 from the values of the key 'I2a1a' of the first dictionary.

I have no idea where to start my script!

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Pierre
  • 21
  • 5
  • Often when you have no idea where to start, it helps to write down the steps you would take if _you_ were to solve this problem without a computer. Then translate your algorithm to code. – Pranav Hosangadi Mar 21 '23 at 16:49

2 Answers2

1

I couldn't understand very well what you are asking even because on the first key you didn't add any index. Anyway, I put down some code that you can edit and use for your needs:

dic = {'I2a1a': ['I2a1a2', 'I2a1a2a', 'I2a1a2a1a2'], 'I2a1b': ['I2a1b1a1a1b1a'], 'I2a1b2': ['I2a1b2a']}


dic2 = {}


for element in dic:
    if len(dic[element]) >1:
        i=0
        while i<len(dic[element]):
            key = element + (str(i))
            dic2[key]=dic[element][i]
            i +=1
    else:
        dic2[element] = dic[element][0]
print(dic2)

The output is:

{'I2a1a0': 'I2a1a2', 'I2a1a1': 'I2a1a2a', 'I2a1a2': 'I2a1a2a1a2', 'I2a1b': 'I2a1b1a1a1b1a', 'I2a1b2': 'I2a1b2a'
cconsta1
  • 737
  • 1
  • 6
  • 20
Carlo 1585
  • 1,455
  • 1
  • 22
  • 40
1

Often when you have no idea where to start, it helps to write down the steps you would take if you were to solve this problem without a computer. Then translate your algorithm to code. For instance:

  1. Iterate over dic.items()
  2. For each key-value pair, create a list containing the key, and then all elements of the value list.
  3. Iterate over consecutive pairs (current_elem, next_elem) in this new list
  4. In this iteration, the current_elem is the key for the new_dic, and next_elem is the value.

Now let's write this as code:

dic = {'I2a1a': ['I2a1a2', 'I2a1a2a', 'I2a1a2a1a2'],
       'I2a1b': ['I2a1b1a1a1b1a'],
       'I2a1b2': ['I2a1b2a']}

new_dic = {}

for key, value in dic.items(): # 1.
    new_elems = [key, *value]  # 2.
    for current_elem, next_elem in zip(new_elems[:-1], new_elems[1:]):  # 3.
        new_dic[current_elem] = next_elem  # 4.

which gives the desired new_dic:

{'I2a1a': 'I2a1a2', 'I2a1a2': 'I2a1a2a', 'I2a1a2a': 'I2a1a2a1a2',
 'I2a1b': 'I2a1b1a1a1b1a',
 'I2a1b2': 'I2a1b2a'}
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70