Home > Mobile >  Printing a particular entry within a dict array in python
Printing a particular entry within a dict array in python

Time:11-20

I have a dict called properties that looks like this.

# Format for properties
# NAME = POS FNAME TYPE PRCHSBLE SUIT PRICE RENT RENTSET RENT1 RENT2 RENT3 RENT4 RENTH HSCOST HTCOST MORT UNMORT
properties = {
    'okr': [1,'Old Kent Road',types["pt"],True,suits["br"],60,2,4,10,39,90,160,250,50,50,30,33]
}

(types and suits are just other dicts). To access this I'm using a function:

def view(prop):
    print(f"Property Name: {properties[prop]}")

property = input("Which Property? ")
view(property)

This works great, until the point where I need to get a particular argument like for instance I need the 5th value, how do I go about doing that? Is it like an array where I use [x]

CodePudding user response:

If you check what type property['okr'] returns (type(properties['okr'])) you will see that it is basically just a list. Therefore, you can access all the elements like in a normal list. Let's say we want to get the road name from okr:

properties['okr'][2]  # will return 'Old Kent Road'

CodePudding user response:

You can stack indexes with square brackets. If you wanted the price of Old Kent Road, you could do properties['okr'][5].

If you want a more robust option, make the data about the house a dict as well instead of a list. This way you can reorder or add new data about each property, or even leave fields blank, without having other code relying on the data being in a specific order. Then you would write properties['okr']['price'], for example.

Defining your own Property class would be the even more robust answer, with class members for each piece of data. That would be the most "correct" OOP way to do it, but if I'm being honest writing 100 lines of boilerplate just to print the name of a house sucks, so you should gauge for yourself how much effort needs to be put into it.

  • Related