-3

I am new to python programming,i have this list:

['NAME surname', 'email', 'Type', 'NAME surname', 'email', 'type',and so on..]

Could I split every tree elements of the list in one dictionary key?

For example:

{'Name surname1':['Name Surname1','email1','type1'],'Name surname2':[name2,email2,type2 and so on]}

I need this because i want to specify one Key and obtain the values of the key,in this case the name email and so on.. I have already a big list populated.

Thanks in advance for the help.

cdm
  • 129
  • 1
  • 4
  • 10

2 Answers2

4

Yes. You can make a dictionary with a list comprehension:

{namelist[i] : namelist[i : i + 3] for i in xrange(0, len(namelist), 3)}

Note that this will only work if your list is always a repetition of name, email, type, and only if all names are unique.

Amy Teegarden
  • 3,842
  • 20
  • 23
1

Yes you can. Here is an example :

>>> d = dict()
>>> d["A"] = ["name","email"]
>>> d["B"] = ["tom","tom@gmail.com"]
>>> print(d)
{'B': ['tom', 'tom@gmail.com'], 'A': ['name', 'email']}

You can access individual lists per key as well :

>>> print(d["A"])
['name', 'email']


Here's more along the lines of what you wanted :

>>> d= dict()
>>> d["Name Surname 1"] = ["Name Surname 1", "email", "type1"]
>>> d["Name Surname 2"] = ["Name Surname 2", "email", "type2"]
>>> d["Name Surname 3"] = ["Name Surname 3", "email", "type3"]
>>> for key in d:
...     print(key)
...     for list_item in d[key]:
...         print("\t%s"%list_item)
... 
Name Surname 3
    Name Surname 3
    email
    type3
Name Surname 1
    Name Surname 1
    email
    type1
Name Surname 2
    Name Surname 2
    email
    type2
Meghdeep Ray
  • 5,262
  • 4
  • 34
  • 58