'How to assign value of key to a list in python?
For example, I have the following:
newdict = {0: [5], 1: [2, 1], 2: [2]}
initiallist = [5,2,2,1]
I would like to get the output: [0,1,2,1].
I tried different methods, but it did not work? Any suggestions? I need help with this.
Solution 1:[1]
Ok, I'm going to go on a bit of a limb here. This gives something close to your desired result:
def get_counts_for_keys(dictionary, keys_to_check):
return [len(dictionary.get(x, [])) for x in keys_to_check]
newdict = {0: [5], 1: [2, 1], 2: [2]}
initiallist = [5,2,2,1]
result = get_counts_for_keys(newdict, initiallist)
print(result) # Prints [0, 1, 1, 2], not [0, 1, 2, 1] as desired.
Is this anything like what you are after, or completely off the mark?
Solution 2:[2]
Answering title's question, you can list dict's items, just as these:
newdict = {0: [5], 1: [2, 1], 2: [2]}
a_list = list(newdict.items())
a_list
[(0, [5]), (1, [2, 1]), (2, [2])]
Then you can get key by their list position, such as:
a_list[0][0], a_list[0][1], a_list[1][0],a_list[1][1],a_list[2][0],a_list[2][1]
(0, [5], 1, [2, 1], 2, [2])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrew McClement |
| Solution 2 | Bruno Takara |
