Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a list of dictionaries. I want to extract the key value pairs from it. And if a dictionary key has multiple values, each key-value pair should be printed separately.

What I have tried:

My list -->
operand=[{"fill_with median":[["f.1_FEB_09","f.1_OCT_09"]]},
              {"fill with mean":[["f.1_FEB_09","f.1_OCT_09"]]},
              {"fill with interpolated values":[["f.1_FEB_09","f.1_OCT_09"]]}, 
              {"fill with mode":["M"]}]



My code:

for i in operand:
    for key, value in i.items():
        print(key, value)


Output received:

fill with median [['f.1_FEB_09', 'f.1_OCT_09']]
fill with mean [['f.1_FEB_09', 'f.1_OCT_09']]
fill with interpolated values [['f.1_FEB_09', 'f.1_OCT_09']]
fill with mode ['M']



Output expected:
fill with median [['f.1_FEB_09']]
fill_with median [['f.1_OCT_09']]

fill with mean [['f.1_FEB_09']]
fill with mean [['f.1_OCT_09']]

fill with interpolated values [['f.1_FEB_09']]
fill with interpolated values [['f.1_OCT_09']]

fill with mode ['M']



Is there a way to get the expected output?
Posted
Updated 20-Feb-23 5:21am
Comments
0x01AA 20-Feb-23 11:02am    
You have one dictionary were the values (of the key/value pair) is a list. Therefore to print that you have to loop over the value- list.
That's it.

From my point of view you have one list too much. But anyway to get the expected result with your current code it would be something like this (take care intendation much probably destroyed in the comment):

for i in operand:
for key, value in i.items():
for listValue in value :
for listListValue in listValue:
print(key, listListValue)
Apoorva 2022 20-Feb-23 11:17am    
Thanks. Got it.

Solved by OP. Please see also comments to the question.
 
Share this answer
 
Comments
Apoorva 2022 20-Feb-23 12:23pm    
I solved it the same way. Thanks:).
0x01AA 20-Feb-23 12:49pm    
I see. Thank you for the vote.
Solution:
for i in operand:
    for key, value in i.items():
      for k in value:
        for m in k:
         print(key, m)



Output:

fill_with median f.1_FEB_09 
fill_with median f.1_OCT_09 
fill with mean f.1_FEB_09 
fill with mean f.1_OCT_09 
fill with interpolated values f.1_FEB_09 
fill with interpolated values f.1_OCT_09 
fill with mode M
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900