1

I have the a list of dicts in python in the following format:

dict1 = [{'Name':'a', 'value':20},{'Name':'b', 'value':10},{'Name':'c', 'value':15}]

I want to output something like this:

dict2 = {'a':20, 'b':10, 'c':15 }

How to do it? Thanks in advance!

2 Answers2

1

Try with a dictionary comprehension:

dict1 = [{'Name':'a', 'value':20},{'Name':'b', 'value':10},{'Name':'c', 'value':15}]
dict2={dc['Name']:dc['value'] for dc in dict1}

Output:

dict2
{'a': 20, 'b': 10, 'c': 15}
MrNobody33
  • 6,413
  • 7
  • 19
  • 1
    Take a look of this link: [dictionary-comprehension](https://www.programiz.com/python-programming/dictionary-comprehension). – MrNobody33 Jul 15 '20 at 06:32
  • 2
    Wow, the better answer is rejected. – Vishesh Mangla Jul 15 '20 at 06:40
  • It's because of I new and I can't understand properly. I am just completing an assignment for my school project. It had a question including this. So I asked it in here. –  Jul 15 '20 at 06:57
  • 1
    Sure @sof1, you should accept the answer that works better for you, and since you're begginer, it's understandably that the other answer was better for you, but, just so you know maybe why this answer is preferable, dictionary comprehension is the most efficent way to create while looping, looping through indexes(as the other answer), it's mostly inneficcient. – MrNobody33 Jul 15 '20 at 16:21
0

I think you can do it with for loop efficiently. Check this:

dict1 = [{'Name':'a', 'value':20},{'Name':'b', 'value':10},{'Name':'c', 'value':15}]
dict2 = dict()
for a in range(len(dict1)):
    dict2[dict1[a].get('Name')] = dict1[a].get('value')
print(dict2)

Output:

{'a': 20, 'b': 10, 'c': 15}
Osadhi Virochana
  • 1,294
  • 2
  • 11
  • 21
  • Actually, it's not efficent looping over indexes: [What is the advantage of a list comprehension over a for loop?](https://stackoverflow.com/a/16341841/13676202) and [Which is the most efficient way to iterate through a list in python?](https://stackoverflow.com/a/10930151/13676202). – MrNobody33 Jul 15 '20 at 17:14
  • @MrNobody33 That was helpful Thank you very much! – Osadhi Virochana Jul 15 '20 at 17:18