Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove items from dictionary if the length of the item is 1 or less

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?

like image 707
Mandingo Avatar asked Nov 24 '18 23:11

Mandingo


People also ask

Can you use LEN () on a dictionary?

To calculate the length of a dictionary, we can use the Python built-in len() method. The len() method returns the number of keys in a Python dictionary.

Can you remove items from a dictionary?

Because key-value pairs in dictionaries are objects, you can delete them using the “del” keyword. The “del” keyword is used to delete a key that does exist.

Which method removes a single element of a dictionary?

The clear() method removes all items from a dictionary and makes it empty.


2 Answers

Just use a dictionary comprehension:

d = {'acd': ['cad'], 'abd': ['bad', 'dab']}
res = {k: v for k, v in d.items() if len(v) >= 2}

Yes, you are creating a new dictionary, but this in itself is not usually a problem. Any solution will take O(n) time.

You can iterate a copy of your dictionary while modifying your original one. However, you should find the dictionary comprehension more efficient. Don't, under any circumstances, remove or add keys while you iterate your original dictionary.

like image 89
jpp Avatar answered Oct 19 '22 22:10

jpp


If you doesn't want to create new dict here's how you could change your code. Here we iterate over copy of our dict and then delete keys of our original dict if length of its value is less than 2.

d = {'acd': ['cad'], 'abd': ['bad', 'dab']}

for key in d.copy():
    if len(d[key]) < 2:
        del d[key]

print(d)
like image 40
Filip Młynarski Avatar answered Oct 19 '22 23:10

Filip Młynarski