Home > front end >  How to print only one list element where list is value in key:value pair
How to print only one list element where list is value in key:value pair

Time:10-30

I'm really new to the world of python, and especially dictionaries, so it is very likely that the answer to my question is quite simple, but I really can't figure it out...

My problem is, that I can't seem to figure out how to access one specific list element at a certain position when I have a dictionary that has a list as it's values.

More specifically I have the following list:

my_books = {'Eragon': [2007,'Paolin'], 'Harry Potter': [1992,'Rowling'], 'Obscura': [2017, 'Canon'], 'Many Wonders': [1964,'Meyers'], 'Never': [2001, 'McKey']}

What I now want to achieve is that it returns me the value at list position 1 and the title of the book (the key) in a very simple, alphabetically sorted table.

Output required:

Canon       Obscura
McKey       Never
Meyers      Many Wonders
Paolin      Eragon
Rowling     Harry Potter

What I can't seem to figure out is how to only print the list element at position 1, instead of the whole list.

My code:

for word in computercollection:
    print(computercollection[word], '       ', word)

My output:

[2007,'Paolin']     Eragon
[1992,'Rowling']    Harry Potter
[2017, 'Canon']     Obscura
[1964,'Meyers']     Many Wonders
[2001, 'McKey']     Never

Anyways, if any one of you could help me out here I would greatly appreciate it!

CodePudding user response:

First, you need to sort the dictionary according the name of the author. Then iterate over the sorted keys and print the required parameters in formatted fashion. For example:

my_books = {
    "Eragon": [2007, "Paolin"],
    "Harry Potter": [1992, "Rowling"],
    "Obscura": [2017, "Canon"],
    "Many Wonders": [1964, "Meyers"],
    "Never": [2001, "McKey"],
}

for key in sorted(my_books, key=lambda k: my_books[k][1]):
    print("{:<15} {:<15}".format(my_books[key][1], key))

Prints:

Canon           Obscura        
McKey           Never          
Meyers          Many Wonders   
Paolin          Eragon         
Rowling         Harry Potter   

CodePudding user response:

A variation on the excellent answer from @Andrej Kesey that doesn't require a lambda but relies on the natural sorting process for tuples:

my_books = {
    "Eragon": [2007, "Paolin"],
    "Harry Potter": [1992, "Rowling"],
    "Obscura": [2017, "Canon"],
    "Many Wonders": [1964, "Meyers"],
    "Never": [2001, "McKey"],
}

for author, title in sorted((value, key) for key, (_, value) in my_books.items()):
    print(f'{author:<12}{title}')

Output:

Canon       Obscura
McKey       Never
Meyers      Many Wonders
Paolin      Eragon
Rowling     Harry Potter

CodePudding user response:

author_book = sorted([(my_books[book][1], book) for book in my_books])

for author, book in author_book:
    print(f"{author:10}{book}")

The explanation:

  1. In the first command we use the list comprehension to create pairs (tuples) (author, book), and then sort this list of tuples.

    • By default, tuples are sorted by their first elements (authors).
      (In the case of the same author, their second element is used as a second sort key.)

    • The my_books[book][1] part of the list comprehension means that

      • we use the book key to obtain its value(my_books[book]), and
      • because this value is a list with the author name in the position 1 (counting from zero), we append [1] to obtain the author name.
  2. In the second command, we print them as individuals elements, using the f-string with the :10 format to reserve enough (10) positions for authors to reach a nice column formatting.

  • Related