2

I intend to get the values for each dictionary in array list and put the values in new dictionary.

There are two key,two values in each dictionary.

This is my array_list.

[{'Name': 'email', 
'Value': '[email protected]'}, 
{'Name': 'name', 
'Value': 'tester'}, 
{'Name': 'address', 
'Value': 'abc'}]

My expected outcome (to get the both values in each dictionary):

{'email': '[email protected]',
 'name': 'tester', 
'address': 'abc'}

My current code:

outcome = {}
x = ""

for i in range(len(array_list)):
    for key,value in array_list[i].items():
        if key == 'Value':
            x = value
        elif key == 'Name': 
            outcome[value] = x

I still not able to get the expected outcome. Any helps?

2
  • 2
    Better to ask dictionary array_list[i] directly with e.g. array_list[i]['Name'] instead of iterating over its items. Commented Dec 13, 2018 at 2:33
  • 2
    The reason you don't get the correct output is that it will only work if the Name is encountered after the Value. It is also inefficient as you should be looking up the keys in the dict instead of iterating until you stumble into them. Commented Dec 13, 2018 at 2:50

2 Answers 2

5
l = [{'Name': 'email', 
'Value': '[email protected]'}, 
{'Name': 'name', 
'Value': 'tester'}, 
{'Name': 'address', 
'Value': 'abc'}]

{k['Name'] : k['Value'] for k in l}

the result is

{'address': 'abc', 'email': '[email protected]', 'name': 'tester'}
Sign up to request clarification or add additional context in comments.

Comments

3

You are almost correct. Just have some problems in if else.

After writing a code you should try to simulate your code by yourself. Please look carefully in you inner for loop. For each iteration either Name or Value will be set as if and elif is mutually exclusive. But the requirement is to create key-value in each iteration.

outcome = {}
array_list = [{'Name': 'email',
               'Value': '[email protected]'},
              {'Name': 'name',
               'Value': 'tester'},
              {'Name': 'address',
               'Value': 'abc'}]
for i in range(len(array_list)):
    keys = array_list[i].keys()
    if 'Name' in keys and 'Value' in keys:
        outcome[array_list[i]['Name']] = array_list[i]['Value']

It is almost same as your code but my thinking is different.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.