For example, now I have the following:
newdict = {0: [5], 1: [2, 1], 2: [2]}
initiallist = [5,2,2,1]
I would like to get the output of [0,1,2,1]
. I tried different methods but it does not work? Any suggestions? Need help on this
CodePudding user response:
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?
CodePudding user response:
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])