0

I am a rookie at python, having a hard time figuering out how lists and dict really works. In my program i have a list that looks like:

Hat =[334,hat,59,200]

that i want to make into a dict, with a key 334 and the vaule = [hat,59,200]. How could i make it so?

phihag
  • 278,196
  • 72
  • 453
  • 469
Bardolf
  • 17
  • 4

1 Answers1

3

Simply extract the first and all further elements with a slice:

{Hat[0]: Hat[1:]}

If you had multiple hats, you can use a dictionary comprehension:

hats = [
    [334,'hat',59,200],
    [123,'chapeau',19,300],
    [999,'hut',1,100],
]

print( {Hat[0]: Hat[1:] for Hat in hats} )
Community
  • 1
  • 1
phihag
  • 278,196
  • 72
  • 453
  • 469
  • Wow did not realize that slice was such a powerful tool, but what if i have a list of several objects (lets say the Hat is just 1 object in a list of several objects). If i would use sliceing, would that apply for each line (given that i use a for loop to go through each line)? – Bardolf Mar 28 '13 at 08:09
  • @RickardSturesson Updated the answer with a solution for that. – phihag Mar 28 '13 at 09:26
  • Thank you! Would you plz look at my edited version, since it involves a more complicated problem? Think I am getting the hang of it, but not sure – Bardolf Apr 05 '13 at 08:12
  • @Bardolf Sorry, but when you add multiple additional questions, you make it hard to follow questions and answers, and your question becomes hard to read for others. Instead, just [ask a new question](http://stackoverflow.com/questions/ask). If necessary, you can link to this one. Thanks! – phihag Apr 05 '13 at 21:01