Amanda Treutler
Amanda Treutler

Reputation: 153

How to combine list of dictionaries based on key

Using this data:

famous_quotes = [
    {"full_name": "Isaac Asimov", "quote": "I do not fear computers. I fear lack of them."},
    {"full_name": "Emo Philips", "quote": "A computer once beat me at chess, but it was no match for me at "
                                          "kick boxing."},
    {"full_name": "Edsger W. Dijkstra", "quote": "Computer Science is no more about computers than astronomy "
                                                 "is about telescopes."},
    {"full_name": "Bill Gates", "quote": "The computer was born to solve problems that did not exist before."},
    {"full_name": "Norman Augustine", "quote": "Software is like entropy: It is difficult to grasp, weighs nothing, "
                                               "and obeys the Second Law of Thermodynamics; i.e., it always increases."},
    {"full_name": "Nathan Myhrvold", "quote": "Software is a gas; it expands to fill its container."},
    {"full_name": "Alan Bennett", "quote": "Standards are always out of date.  That’s what makes them standards."}
]

I'm trying to print out the data in the following format:

"The inspiring quote" - Last name, First name

This is what I've got so far:

quote_names = [k['full_name'] for k in famous_quotes]
quote = [i['quote'] for i in famous_quotes]

print(f"\"{quote[0]}\" - {quote_names[0]} ")
print(f"\"{quote[1]}\" - {quote_names[1]} ")
print(f"\"{quote[2]}\" - {quote_names[2]} ")
print(f"\"{quote[3]}\" - {quote_names[3]} ")
print(f"\"{quote[4]}\" - {quote_names[4]} ")
print(f"\"{quote[5]}\" - {quote_names[5]} ")
print(f"\"{quote[6]}\" - {quote_names[6]} ")

It returns the data in this format:

"I do not fear computers. I fear lack of them." - Isaac Asimov

This is pretty close to what I want, but I'm sure this was not the best way to do this. Also, I can't figure out how to reverse the first and last name (or access each piece individually).

Thank you!

Upvotes: 0

Views: 60

Answers (3)

Ender Look
Ender Look

Reputation: 2401

Why not something like this:

>>> for _ in famous_quotes:
...    print(f'"{_["quote"]}\" - {" ".join(_["full_name"].split(" ")[::-1])}')
"I do not fear computers. I fear lack of them." - Asimov Isaac
"A computer once beat me at chess, but it was no match for me at kick boxing." - Philips Emo
"Computer Science is no more about computers than astronomy is about telescopes." - Dijkstra W. Edsger
"The computer was born to solve problems that did not exist before." - Gates Bill
"Software is like entropy: It is difficult to grasp, weighs nothing, and obeys the Second Law of Thermodynamics; i.e., it always increases." - Augustine Norman
"Software is a gas; it expands to fill its container." - Myhrvold Nathan
"Standards are always out of date.  That’s what makes them standards." - Bennett Alan

For better understanding, it can be expanded into:

for _ in famous_quotes:
    quote = _["quote"]
    name_list = _["full_name"].split(" ")    
    reversed_name = " ".join(name_list[::-1])    # name_list[::-1] does the same of name_list.reverse() but instead of change the current list, it returns a new list
    print(f'"{quote} - {reversed_name}')

Or contracted to:

>>> [print(f'"{_["quote"]}\" - {" ".join(_["full_name"].split(" ")[::-1])}') for _ in famous_quotes]

Be warned that you don't need the list which is produced by the list comprehension. So this could be saw as a bad practice.

Upvotes: 0

Equinox
Equinox

Reputation: 6748

Step by step:

1. Each quote is stored as a dictionary in array.
2. Iterate over the array
3.   we can access dictionary values by using key
4.   get the qoute
5.   get the full_name
6.   split it on spaces "a b c ".split(' ') = ['a','b','c']
7.   print the last element
8.   print the all elements except last element 

for single_qoute in famous_quotes:
    full_name_split = single_qoute['full_name'].split(' ')
    print(single_qoute['quote'],' -',full_name_split[-1],"".join(full_name_split[:-1]))     

Output:

I do not fear computers. I fear lack of them.  - Asimov Isaac
A computer once beat me at chess, but it was no match for me at kick boxing.  - Philips Emo
Computer Science is no more about computers than astronomy is about telescopes.  - Dijkstra EdsgerW.
The computer was born to solve problems that did not exist before.  - Gates Bill
Software is like entropy: It is difficult to grasp, weighs nothing, and obeys the Second Law of Thermodynamics; i.e., it always increases.  - Augustine Norman
Software is a gas; it expands to fill its container.  - Myhrvold Nathan
Standards are always out of date.  That’s what makes them standards.  - Bennett Alan

Upvotes: 1

Austin
Austin

Reputation: 26039

Use a loop with f-string to format strings:

famous_quotes = [
    {"full_name": "Isaac Asimov", "quote": "I do not fear computers. I fear lack of them."},
    {"full_name": "Emo Philips", "quote": "A computer once beat me at chess, but it was no match for me at "
                                          "kick boxing."},
    {"full_name": "Edsger W. Dijkstra", "quote": "Computer Science is no more about computers than astronomy "
                                                 "is about telescopes."},
    {"full_name": "Bill Gates", "quote": "The computer was born to solve problems that did not exist before."},
    {"full_name": "Norman Augustine", "quote": "Software is like entropy: It is difficult to grasp, weighs nothing, "
                                               "and obeys the Second Law of Thermodynamics; i.e., it always increases."},
    {"full_name": "Nathan Myhrvold", "quote": "Software is a gas; it expands to fill its container."},
    {"full_name": "Alan Bennett", "quote": "Standards are always out of date.  That’s what makes them standards."}
]

for x in famous_quotes:
    print(f"\"{x['quote']}\" - {' '.join(reversed(x['full_name'].split()))}")

# "I do not fear computers. I fear lack of them." - Asimov Isaac                                                            
# "A computer once beat me at chess, but it was no match for me at kick boxing." - Philips Emo
# "Computer Science is no more about computers than astronomy is about telescopes." - Dijkstra W. Edsger                
# "The computer was born to solve problems that did not exist before." - Gates Bill                                       
# "Software is like entropy: It is difficult to grasp, weighs nothing, and obeys the Second Law of Thermodynamics; i.e., it always increases." - Augustine Norman                       
# "Software is a gas; it expands to fill its container." - Myhrvold Nathan                                                
# "Standards are always out of date.  That’s what makes them standards." - Bennett Alan

Upvotes: 2

Related Questions