Is there a way to remove a key from a dictionary using it's index position (if it has one) instead of using the actual key (to avoid e.g. del d['key']
, but use index position instead)?
If there is then don't bother reading the rest of this question as that's what I'm looking for too.
So, as an example for my case, I have the dictionary d which uses lists for the values:
d = {'acd': ['cad'], 'abd': ['bad', 'dab']}
I want to remove each key completely from such dictionary whose value's items have a length of less than 2 (so if there's only 1 item).
So, in this example, I would want to remove the key 'acd'
because it's value's list only has 1 item ['cad']
. 'abd'
has 2 items ['bad', 'dab']
, so I don't want to delete it - only if it contains 1 or less item. This dictionary is just an example - I am working with a much bigger version than this and I need it to remove all of the single item value keys.
I wrote this for testing but I'm not sure how to go about removing the keys I want - or determing what they are.
d = {'acd': ['cad'], 'abd': ['bad', 'dab']}
index_pos = 0
for i in d.values():
#Testing and seeing stuff
print("pos:", index_pos)
print(i)
print(len(i))
if len(i) < 2:
del d[???]
#What do I do?
index_pos += 1
I used index_pos because I thought it might be useful but I'm not sure.
I know I can delete an entry from the dictionary using
del d['key']
But how do I avoid using the key and e.g. use the index position instead, or how do I find out what the key is, so I can delete it?