Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list based on name in the list [duplicate]

Tags:

python

I have a list1 like below

list1 = ['mike', 'sam', 'paul', 'pam', 'lion']

One by one, I can specify a list name like below.

for item in list1:
     for item in line:
          mikelist = []
          mikelist.append()

for item in list1:
     for item in line:
          samlist = []
          samlist.append()

for item in list1:
     for item in line:
          paullist = []
          paullist.append()

And so forth. Instead of specifying the name in the list to create new list and append, how do I take the item from the list1 and automatically create list in that for loop line here for all the items in list1?

 for item in line:
      namefromthelist = []
      namefromthelist.append()
like image 465
user10737394 Avatar asked Oct 27 '25 00:10

user10737394


1 Answers

Create a dictionary with the names as keys and lists as values:

dict = {}
list1 = ['mike', 'sam', 'paul', 'pam', 'lion']

for i in list1:
    dict[i] = []
print(dict)

Output:

{'mike': [], 'lion': [], 'paul': [], 'sam': [], 'pam': []}

You can then use it like this:

dict['mike'].append('blah')
print(dict['mike'])
like image 156
glhr Avatar answered Oct 28 '25 14:10

glhr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!