Home > OS >  How to use a dictionary to append values to a list?
How to use a dictionary to append values to a list?

Time:09-16

Trying to solve a leetcode problem right now and think I have an idea for a solution but need some help. I am given 2 lists: 1 is a list of values, and the other is the index value where I should place such values. Such as below:

nums = [1, 5, 3]
index = [0, 1, 2]

So, I would have to append number 1 at index 0, 5 at index 1, etc.

I have solved the problem with simple while loop but now I want to solve the problem with a dictionary, so I have made this so far:

 list2 = []

 ans = dict(zip(nums, index))
        
 list2.insert(someindex, somenumber)

My question is how I can access the data in the dictionary to finish my insert command. how can I replace the code at 'someindex' and 'somenumber' to represent the index and corresponding value stored in my dictionary? Is this possible? Thanks for the help

CodePudding user response:

if that is the case, you could order your code as follow and get a list from the dictionary values you are building there, something like this might help you solve the issue, if I understood what you are trying to accomplish with this:

nums = [1, 5, 3]
index = [0, 1, 2]
list2 = list(dict(zip(index,nums)).values())
print(list2)

CodePudding user response:

You could do something like this:

nums = [1, 5, 3]
index = [0, 1, 2]
ans = dict(zip(index, nums))
list2 = [0 for _ in range(len(ans))]

for index, value in ans.items():
    list2[index] = value

Note that you must instantiate list2 the way described because you'll get index out of range exception otherwise.

CodePudding user response:

This is a very convoluted way of doing things. (keep it simple. for loop is much better) but here are a few ways.

list(map(lambda x: x[0], sorted(ans.items(), key=lambda x: x[1])))


[x[0] for x in sorted(ans.items(), key=lambda x: x[1])]

Need sorted here because you never mentioned that indices list is sorted

Going one step back you do not need to create a dict. zip object would suffice

[x[0] for x in sorted(zip(nums, index), key=lambda x: x[1])]

this would save unnecessary transformation to dict

  • Related