Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary in a list
#1
Hi,
I'm learning French and Python, and I thought I'd combine the two. My goal is to make a glossary written in Python, where each word is a dictionary with three keys (word category, article and chapter in which it first appears) and values. I'd like to store those words in a list; this list is for nouns. So far I've come up with this (indentation is screwed up, but originally correct):

voyager_glossary_noun = []

voyage = {
    'category': 'noun',
    'article': 'le',
    'chapter': '1a',
    }

voyager_glossary_noun.append(voyage)

quai = {
    'category': 'noun',
    'article': 'le',
    'chapter': '1a',
    }

voyager_glossary_noun.append(quai)
I have trouble accessing the various data. I'd like to have an output like this:

quai:
* noun
* le
* chapter 1a

I've written this:

1. for word in voyager_glossary_noun:
2.     
3.     for key, value in voyage.items():
4.         msg = f"\t* {value}"
5.         print(msg)
I don't understand how to display the word itself, and I get the impression that I should be able to do that with one line of code on the second line. Any tips? I'm an almost total beginner, and simple code and explanation would be greatly appreciated.
Gribouillis write Dec-27-2023, 03:19 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
(Dec-27-2023, 01:30 PM)bashage Wrote: I don't understand how to display the word itself,
The word itself would be a string, and it is saved nowhere.
voyage = {...} is a dictionary, a variable name with no reference to the string' voyage'.
That is why I always try to apply the so called "Hungarian notation", where you prefix the name of a
variable with it's type.
So dictVoyage = {...} or lstVoyage = [] or setVoyage = (...)
You will need to repeat Voyage as an element of the dict, altough there might be better ways to do this.
Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply
#3
I would make a class for the words. It will save a ton of typing later.
from dataclasses import dataclass


@dataclass
class Word:
    category: str
    article: str
    chapter: str


glossary = {"voyage": Word("noun", "le", "la"), "quai": Word("noun", "le", "la")}

for word, entry in glossary.items():
    print(word, entry)
Output:
voyage Word(category='noun', article='le', chapter='la') quai Word(category='noun', article='le', chapter='la')
I might make the glossary a class too.
from dataclasses import dataclass


@dataclass
class Word:
    category: str
    article: str
    chapter: str


class Glossary:
    def __init__(self):
        self.words = {}

    def noun(self, word: str, article: str, chapter: str):
        self.words[word] = Word("noun", article, chapter)
        return self

    def verb(self, word: str, article: str, chapter: str):
        self.words[word] = Word("verb", article, chapter)
        return self

    @property
    def nouns(self):
        return {
            word: entry
            for word, entry in self.words.items()
            if entry.category == "noun"
        }

    @property
    def verbs(self):
        return {
            word: entry
            for word, entry in self.words.items()
            if entry.category == "verb"
        }

    def __getitem__(self, word):
        return self.words[word]

    def __iter__(self):
        return iter(self.words)


glossary = Glossary()
glossary.noun("voyage", "le", "la")
glossary.noun("quai", "le", "la")

for word in glossary.nouns:
    print(word, glossary[word])

print("Lookup voyage", glossary["voyage"])
Output:
voyage Word(category='noun', article='le', chapter='la') quai Word(category='noun', article='le', chapter='la') Lookup voyage Word(category='noun', article='le', chapter='la')
sgrey likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  filtering a list of dictionary as per given criteria jss 5 697 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  Sort a list of dictionaries by the only dictionary key Calab 1 498 Oct-27-2023, 03:03 PM
Last Post: buran
  How to add list to dictionary? Kull_Khan 3 1,015 Apr-04-2023, 08:35 AM
Last Post: ClaytonMorrison
  check if element is in a list in a dictionary value ambrozote 4 1,991 May-11-2022, 06:05 PM
Last Post: deanhystad
  Dictionary from a list failed, help needed leoahum 7 1,977 Apr-28-2022, 06:59 AM
Last Post: buran
  how to assign items from a list to a dictionary CompleteNewb 3 1,594 Mar-19-2022, 01:25 AM
Last Post: deanhystad
  Python, how to manage multiple data in list or dictionary with calculations and FIFO Mikeardy 8 2,619 Dec-31-2021, 07:47 AM
Last Post: Mikeardy
  Class-Aggregation and creating a list/dictionary IoannisDem 1 1,929 Oct-03-2021, 05:16 PM
Last Post: Yoriz
  Python dictionary with values as list to CSV Sritej26 4 3,028 Mar-27-2021, 05:53 PM
Last Post: Sritej26
  convert List with dictionaries to a single dictionary iamaghost 3 2,880 Jan-22-2021, 03:56 PM
Last Post: iamaghost

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020