igorkf
igorkf

Reputation: 3575

Filter all the dictionary based on values of just one key

I have this dict:

d1 = {"date":["2019-11","2019-11","2019-12","2019-12","2020-01","2020-01"],
      "shares":[28,16,5,10,1,1],
      "target":["INSTAGRAM","TEXT","INSTAGRAM","TEXT","INSTAGRAM","TEXT"]
     }

I want to filter all the d1 dictionary only for target = INSTAGRAM, without using pandas. So this is the expected result:

{"date":["2019-11","2019-12","2020-01"],
 "shares":[28,5,1],
 "target":["INSTAGRAM","INSTAGRAM","INSTAGRAM"]
}

Upvotes: 0

Views: 50

Answers (2)

yatu
yatu

Reputation: 88305

Using a defaultdict:

from collections import defaultdict
d = defaultdict(list)
for i, target in enumerate(d1['target']):
    if target == 'INSTAGRAM':
        for k,v in d1.items():
            d[k].append(v[i])

print(d)
defaultdict(list,
            {'date': ['2019-11', '2019-12', '2020-01'],
             'shares': [28, 5, 1],
             'target': ['INSTAGRAM', 'INSTAGRAM', 'INSTAGRAM']})

If you want to avoid any imports and use python's dict class:

d = dict()
for i, target in enumerate(d1['target']):
    if target == 'INSTAGRAM':
        for k,v in d1.items():
            if k in d.keys():
                d[k].append(v[i])
            else:
                d[k] = [v[i]]

Upvotes: 2

David Garaña
David Garaña

Reputation: 945

This should do the trick:

def filter_by_key(key, value, _dict):
    """ Filter a dictionary by it's key value

    :param str key: Dictionary key to inspect
    :param str value: Value to look for inside the dictionary key
    :param dict _dict: Dictionary to inspect
    :return: Dictionary with filter applied
    """

    indexes = [index for index, item in enumerate(_dict[key])
               if _dict[key][index] == value]

    result_dict = {}
    for key, value in a.iteritems():
        result_dict[key] = [_dict[key][index] for index in indexes]
    return result_dict
a = {"date":["2019-11","2019-11","2019-12","2019-12","2020-01","2020-01"],
      "shares":[28,16,5,10,1,1],
      "target":["INSTAGRAM","TEXT","INSTAGRAM","TEXT","INSTAGRAM","TEXT"]
     }


result = filter_by_key('target', 'INSTAGRAM', a)

Upvotes: 1

Related Questions