6

To convert a list into a dictionary with key as the index of the element and values as the value in the list. i have tried to create it but was facing errors.below is my current code

for each in list:
    dict[each] = list[each]

what is wrong in my code. i am a beginner in python.

justin mooc
  • 61
  • 1
  • 1
  • 5
  • You have not defined `dict` as a dictionary object. Also you are assigning `each` value of the list both as key and value of the dictionary. – Soumendra May 19 '18 at 17:59
  • Welcome to SO, You are actually applying a for loop on your on your list without using indexing method, you are using a direct approach - simple iterating over your elements and the value of `each` is basically the element value not the index value, if you want to work with indexing method try this - `for i in range(0,len(list): dict[i] = list[i]`. This will work – Keshav Garg May 19 '18 at 18:02
  • What question isn't market duplicate anymore? Waste of time answering SMH – Aaron Brandhagen May 19 '18 at 18:20
  • @AaronBrandhagen If it's a duplicate, it should be marked as such. If you think that wastes your time, consider posting your answer on the duplicate instead. That's the whole point - we want the answers to be in one place. – Aran-Fey May 19 '18 at 18:23
  • Aran, I know what you did was justified. But why would I search especially when it's a race to get the first answer in? Also, how does it hurt to have a similar question answered in a variety of ways? The titles to both are different, meaning a person searching for this answer later may only pick up one or the other with a google search. With only one, it's possible their search would miss the only available posting when it would have caught the other. – Aaron Brandhagen May 19 '18 at 18:28
  • 2
    @AaronBrandhagen That's why we don't *delete* duplicate questions. Questions marked as duplicate stay around to serve as guide posts. But we don't want the *answers* to be fragmented. We want all the answers to be in the same place because it makes it easier to find them and vote on them and comment on them. The existing answers have already been voted on, and the best ones have risen to the top. If you start reposting the same answers instead of closing the question as a dupe, all that voting and commenting has to happen *again*. – Aran-Fey May 19 '18 at 18:38
  • 1
    @AaronBrandhagen I've lost count how many times some n00b has (re-)posted a garbage answer (think [`eval`](https://docs.python.org/3/library/functions.html#eval) or the like) and I've had to explain why that is bad and yadda yadda. I'm not interested in repeating myself every time someone decides to repost an answer I've commented on in the past. It's a waste of everyone's time. We're all better off if every answer exists exactly once, and they all exist on the same question. – Aran-Fey May 19 '18 at 18:40
  • I know, you are correct. Funny though, I just got reprimanded from another poster for worrying about getting votes/accepted answers in that it's all about the future readers. Just a little ironic. I actually just email SE as to whether dups are kept. I'm do analysis on the entire SO data dump and wanted to see if dups would be part of the analysis. Good to know! – Aaron Brandhagen May 19 '18 at 18:42
  • Truth. But remember, Aran: it's much easier for someone to search for a posting that to post about it. They aren't doing (most of the time) out of laziness, that would make no sense. They cant find the answer - which to my point is a good reason to have the multiple areas where a question can be pulled from a search. Maybe a good idea would be to merge duplicates with the original? It's a very simple SQL operation....who knows! – Aaron Brandhagen May 19 '18 at 18:45
  • My final note: adept programmers don't realize how hard it is to find the words to search effectively for an answer a beginner seeks. I distinctly recall that being my #1 largest frustration. All point are valid from you, like I said. But there is perspective to be had. Cheers! – Aaron Brandhagen May 19 '18 at 18:55

3 Answers3

12

Try using enumerate! It's nifty:

list = ['a','b','c']

print(dict(enumerate(list))) # >>> {0: 'a', 1: 'b', 2: 'c'}

what is wrong with your code is that you are taking two elements of a list (by subscripting them with the list[value] syntax) and setting them equal to each other.

What you meant to do:

   d = {}
    l = ['a','b','c']
    for k,v in enumerate(l):
        d[k] = v

What this does:

Enumerating a sequence gives you a tuple where an integer is paired with the value of the sequence.Like in my list above, the enumerate(list) itself would be:

for k in enumerate([1,2,3]):
print(k)

Result: (0, 1) (1, 2) (2, 3)

The k and v in the loop first for loop I wrote unpacks the tuples (k= the index 0 of the tuple, v = the second), and the predefined dict (d in my case) sets the enumerate value (d[k], the key) to the value k (the second value of the tuple after enumeration)

Hope this makes sense!

4
dict = {}
for each in list:
    dict[each] = list[each]

Take for array list = [1,2,34,22] an example

dict[1] = list[1]  # list[1] = 2
dict[2] = list[2]  # list[2] = 34
dict[34] = list[34]  # Error size is just 4 , accessing list[34] will give index error

Try this simple code

a = [1,2,34,22]

dict = {}
for i in  range(len(a)):
  dict[i]=a[i]
print(dict)
shubham johar
  • 268
  • 1
  • 9
2

the following code will work

lst = [1,2,3,4]
result = {i:j for i,j in enumerate(lst)}
rawwar
  • 4,834
  • 9
  • 32
  • 57