Mikael Ken
Mikael Ken

Reputation: 41

Remove item by value from another column of a list of dicts

Let's presume I have a list of dicts. Each dict contains a key from and another key named to. Now, I want this: in the second and following appearances of a from key where the value of the to key differs from the value of the first to key associated with that from key, that dict should be removed from the list.

Example:

[ {'from': '67f', 'to': 'f9b'},
 {'from': '67f', 'to': 'f9b'},
 {'from': '67f', 'to': 'f9b'},
 {'from': 'f9b', 'to': '67f'},
 {'from': 'f9b', 'to': '21g'} ]

would become this:

[ {'from': '67f', 'to': 'f9b'},
 {'from': '67f', 'to': 'f9b'},
 {'from': '67f', 'to': 'f9b'},
 {'from': 'f9b', 'to': '21g'} ]

Upvotes: 0

Views: 46

Answers (2)

Vinit Neogi
Vinit Neogi

Reputation: 386

You can try something like this:

data = [ {'from': '67f', 'to': 'f9b'},
 {'from': '67f', 'to': 'f9b'},
 {'from': '67f', 'to': 'f9b'},
 {'from': 'f9b', 'to': '67f'},
 {'from': 'f9b', 'to': '21g'} ]

final_data = []

for i in range(len(data)):
  if(i == 0 or data[i]['to'] != data[i-1]['from']):
    final_data.append(data[i])

print(final_data)

Loop over the data and check the condition for all items except first one.

Upvotes: 1

Bendang
Bendang

Reputation: 321

This can help.

list_dict = [ {'from': '67f', 'to': 'f9b'}, {'from': '67f', 'to': 'f9b'}, 
              {'from': '67f', 'to': 'f9b'}, {'from': 'f9b', 'to': '67f'}, 
              {'from': 'f9b', 'to': '21g'}]
not_wanted_to_keys = []
wanted_list_dict = []
for my_dict in list_dict:
    not_wanted_to_keys.append(my_dict['from'])
    if my_dict['to'] not in not_wanted_to_keys:
        wanted_list_dict.append(my_dict)
print(wanted_list_dict)

Upvotes: 3

Related Questions