0

I have a dictionary with the key values like this.

>>>dict.keys()
[('4', '12'), (('8', '9'), ('10', '11')), (('8', '10'), ('12', '14')), (('10', '11'), ('14', '15'))]

I want to format the key values so that it looks like this.

>>>dict.keys()
[('4', '12'), ('8', '9', '10', '11'), ('8', '10', '12', '14'), ('10', '11', '14', '15')]   

The inner brackets are removed in the expected output. I tried converting the keys to a list and then formatting the values, but it didn't give the expected output.

Thanks.

EDIT

The values in the dictionary corresponding to the keys remain the same. Also, I want to change the key formatting directly in the dictionary instead of converting it to a list as this raises error in other parts of the code.

Input dictionary:

{('4', '12'): '-100', (('8', '9'), ('10', '11')): '10--', (('8', '10'), ('12', '14')): '1--0', (('10', '11'), ('14', '15')): '1-1-'}

Expected Output Dictionary:

{('4', '12'): '-100', ('8', '9', '10', '11'): '10--', ('8', '10', '12', '14'): '1--0', ('10', '11', '14', '15'): '1-1-'}
Abhi
  • 3,431
  • 1
  • 17
  • 35
  • Can you post what you've tried? For easier look up, what you are trying to do is `flatten` a tuple. – FHTMitchell Oct 17 '18 at 08:51
  • 2
    You'll find a partial solution over at https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python – AKX Oct 17 '18 at 08:52
  • What should happen to the values then? Can you show us the whole dict? – timgeb Oct 17 '18 at 08:54
  • Apply the solutions from the linked post to each of your keys; your keys are arbitrarily nested. – Martijn Pieters Oct 17 '18 at 09:03
  • Here is the solution: `def is_nested_tuple(tupl): return any(isinstance(elem, tuple) for elem in tupl) lst = [tuple(chain(*tupl)) if is_nested_tuple(tupl) else tupl for tupl in lst]` – Mihai Alexandru-Ionut Oct 17 '18 at 09:10
  • If you also need to update the keys in the dictionary then you'd either have to delete the old key and set the value again for the new key, or use a dict comprehension to build a new dictionary with the transformed keys. – Martijn Pieters Oct 17 '18 at 09:32

1 Answers1

2

Try using chain()

def is_nested_tuple(tupl): 
      return any(isinstance(elem, tuple) for elem in tupl) 

lst = [tuple(chain(*tupl)) if is_nested_tuple(tupl) else tupl for tupl in lst]

Output

=> [('4', '12'), ('8', '9', '10', '11'), ('8', '10', '12', '14'), ('10', '11', '14', '15')]
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
eiram_mahera
  • 950
  • 9
  • 25