0

I need some kind of loop or filter that removes every entry that doesn't contain the string "id" in it.

someDict = { 'id1': [('id1'), ('book'), ('sauce'), ('pencil')],
             'id2': [('id2'), ('id4'),  ('id5'), ('pens') , ('id6'), ('stuff')],
             'id3': [('id3'), ('id81'), ('van'), ('garage')]}

So after, it would look like this:

someDict = { 'id1': [('id1')],
             'id2': [('id2'), ('id4'), ('id5'), ('id6')],
             'id3': [('id3'), ('id81') ]}

I'm beyond stumped. I've been trying to figure this out for three hours. Any help would be greatly appreciated.

I tried this, but I'm not good with filters like these. It was supposed to remove everything in the dictionary that didn't have "id" in it, but it didn't work.

#someDict = { k : v for k, v in someDict.items() if 'id' in v }

Then I tried to figure out a loop, but couldn't get this working either.

for key, value in someDict.items():
    for x in value:
        if not "id" in x:
            value.remove(x)```
Lip Lin
  • 9
  • 4
  • You need to iterate over a copy of dict. If you delete items during iteration, it will throw RunTimeError – Yoshikage Kira Jun 15 '21 at 07:22
  • [How to delete items from a dictionary while iterating over it?](https://stackoverflow.com/questions/5384914/how-to-delete-items-from-a-dictionary-while-iterating-over-it) – Yoshikage Kira Jun 15 '21 at 07:24
  • Apart from what @Goion suggested `v` or `value` values are basically a list of tuples. your code would have worked if they were just string. You need to keep that in mind and modify your logic accordingly – Roy Jun 15 '21 at 07:26
  • However, If I may suggest, why use tuples when all the tuples have only single entries? In case you can modify this data structure I would suggest instead of using List of Tuple of String, use List of String. – Roy Jun 15 '21 at 07:29

2 Answers2

1

this should work:

{k: [e for e in v if 'id' in e] for k, v in someDict.items()}

I don't know why you write parentheses inside your lists. If you want to make tuples, make sure to add a , at the end of the tuple, like this: ('id1',). If this is what you intended to do, consider this code instead:

someDict = { 'id1': [('id1',), ('book',), ('sauce',), ('pencil',)],
             'id2': [('id2',), ('id4',),  ('id5',), ('pens',) , ('id6',), ('stuff',)],
             'id3': [('id3',), ('id81',), ('van',), ('garage',)]}

id_dict = {k: [e for e in v if 'id' in e[0]] for k, v in someDict.items()}
frogger
  • 41
  • 4
0

Try this:

for value in someDict.values():
    for i in value:
        if i[0:2] != 'id':
            value.remove(i)

You don't need to iterate complete items(key and values), rather just get all the values and then check condition on each value element.

Aven Desta
  • 2,114
  • 12
  • 27
Utkarsh Pal
  • 4,079
  • 1
  • 5
  • 14