Home > other >  How do I give the list an index name?
How do I give the list an index name?

Time:10-28

I've seen something like this construction somewhere:

list.append({
   'title': scName,
   'link': scLink,
})

print('Names:', list['title'])
print('Links:', list['link'])

Can you please show a working example?

CodePudding user response:

Here, the dict is being appended to a list. And to use inner data, we've to put list[<index_of_inner_dict>][key_of_that_data]. In short, we've to go to the whole inner data index, then the index of required value. Here we have only one dict, it is simply list[0]. Also, scName and scLink are not defined, I'm assuming that they are simple strings. Your code:

l=[]
l.append({
   'title': "scName",
   'link': "scLink"
})
print (l)

print('Names:', l[0]['title'])       
print('Links:', l[0]['link'])

CodePudding user response:

What I believe you are asking is for someone to give you an example of how to use a dictionary. To give some background on dictionaries, they store information in key-value pairs. The key, which is the "index name" you mentioned in your title is mapped to a value stored. You can read here if you are still confused.

For the code example you gave, what it looks like you are attempting to do is add multiple dictionaries to a list and then access those values. Here is an example.

lst_of_employees = []

lst_of_employees.append({"name": "John", "salary": "10000"})
lst_of_employees.append({"name": "Jane", "salary": "20000"})

for emp in lst_of_employees:
    print(f"{emp['name']} makes ${emp['salary']} a year.")

You can make the value of the key-value pair whatever you would like. Here is an example with the value stored at the key "salary" as another dictionary.

lst_of_employees = []

lst_of_employees.append({"name": "John", "salary": {"base": 8000, "bonus": 2000}})
lst_of_employees.append({"name": "Jane", "salary": {"base": 15000, "bonus": 5000}})

for emp in lst_of_employees:
    employee = emp["name"]
    base = emp["salary"]["base"]
    bonus = emp["salary"]["bonus"]

    print(f"{emp['name']} makes ${base bonus} a year.")
  • Related