1

I want to replace the key-value pair in a directory with the value from the same key-value pair. In simple words, I want to replace

{k1:{key1:value1},k2:{Key2:value2}} with {k1:value1,k2:value2}

in simple words: {key1:value1} gets replaced with value1

My input is {'times': {0: 3284566678.449864},
 'C0PLUSA': {0: 2.4529042386185244e-06},
 'C1PLUSA': {0: 2.215571719760855e-06},
 'I0PLUSA': {0: 1200.000000000029},
 'M1BA': {0: 1.1971391933999447e-05},
 'M1DA': {0: 2.5217060699404884e-06},
 'M1GA': {0: 1.0922075194286918e-05},
 'M1SA': {0: 0.0006776339108859284},
 'M2BA': {0: 1.7152638293476106e-05}}

Code:

for i, key,value in a.items:
    a[key][value] = value.values()

But I get an error saying this object is not iterable.

for node,value in a.items():
    a = a.replace(node.values(), value.values())

but it still gives me an error.

I am expecting to get an output as:

{'times':3284566678.449864,
     'C0PLUSA': 2.4529042386185244e-06,
     'C1PLUSA': 2.215571719760855e-06,
     'I0PLUSA': 1200.000000000029,
     'M1BA':  1.1971391933999447e-05,
     'M1DA':  2.5217060699404884e-06,
     'M1GA':  1.0922075194286918e-05,
     'M1SA':  0.0006776339108859284,
     'M2BA':  1.7152638293476106e-05}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nisharg
  • 39
  • 6

1 Answers1

2

If all the keys in the inner dictionaries are 0 you can just do:

{k:v[0] for k,v in data.items()}

In case you want to ignore the keys of the inner dictionaries without knowing the value, you can see how this example works:

>>> data={'k1': {'key1': 'value1'}, 'k2': {'key2': 'value2'}}
>>> {k:list(v.values())[0] for k,v in data.items()}
{'k1': 'value1', 'k2': 'value2'}
jacalvo
  • 656
  • 5
  • 14
  • Thank you jacalvo it works perfectly fine for this case. Could I please ask for an explanation for this . if my inner dictionary had different keys, then what would work for it. Thanks for your time and help – Nisharg Jun 27 '19 at 08:12
  • You are welcome. I've edited the answer with a more generic example. Hope it helps. – jacalvo Jun 27 '19 at 08:30
  • Thanks a lot jacalvo. Appreciate your help. – Nisharg Jun 27 '19 at 08:34