-1

I have dictionary in format "site_mame": (side_id, frequency):

d=[{'fpdownload2.macromedia.com': (1, 88),
  'laposte.net': (2, 23),
  'www.laposte.net': (3, 119),
  'www.google.com': (4, 5441),
  'match.rtbidder.net': (5, 84),
  'x2.vindicosuite.com': (6, 37),
  'rp.gwallet.com': (7, 88)}]

Is there a smart way to filter dictionary d by value so that I have only those positions, where frequency is less than 100? For example:

d=[{'fpdownload2.macromedia.com': (1, 88),
  'laposte.net': (2, 23),
  'match.rtbidder.net': (5, 84),
  'x2.vindicosuite.com': (6, 37),
  'rp.gwallet.com': (7, 88)}]

I don't want to use loops, just looking for smart and efficient solution...

martineau
  • 119,623
  • 25
  • 170
  • 301
elenaby
  • 167
  • 2
  • 11

3 Answers3

4

You can use a dictionary comprehension with unpacking for a more Pythonic result:

d=[{'fpdownload2.macromedia.com': (1, 88),
  'laposte.net': (2, 23),
  'www.laposte.net': (3, 119),
  'www.google.com': (4, 5441),
 'match.rtbidder.net': (5, 84),
 'x2.vindicosuite.com': (6, 37),
 'rp.gwallet.com': (7, 88)}]
new_data = [{a:(b, c) for a, (b, c) in d[0].items() if c < 100}]

Output:

[{'laposte.net': (2, 23), 'fpdownload2.macromedia.com': (1, 88), 'match.rtbidder.net': (5, 84), 'x2.vindicosuite.com': (6, 37), 'rp.gwallet.com': (7, 88)}]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
1

You can use a dictionary comprehension to do the filtering:

d = {
    'fpdownload2.macromedia.com': (1, 88),
    'laposte.net': (2, 23),
    'www.laposte.net': (3, 119),
    'www.google.com': (4, 5441),
    'match.rtbidder.net': (5, 84),
    'x2.vindicosuite.com': (6, 37),
    'rp.gwallet.com': (7, 88),
}

d_filtered = {
    k: v
    for k, v in d.items()
    if v[1] < 100
}
Tom Dalton
  • 6,122
  • 24
  • 35
0

What you want is a dictionary comprehension. I'll show it with a different example:

d = {'spam': 120, 'eggs': 20, 'ham': 37, 'cheese': 101}

d = {key: value for key, value in d.items() if value >= 100}

If you don't already understand list comprehensions, this probably looks like magic that you won't be able to maintain and debug, so I'll show you how to break it out into an explicit loop statement that you should be able to understand easily:

new_d = {}
for key, value in d.items():
    if value >= 100:
        new_d[key] = value

If you can't figure out how to turn that back into the comprehension, just use the statement version until you learn a bit more; it's a bit more verbose, but better to have code you can think through in your head.

Your problem is slightly more complicated, because the values aren't just a number but a tuple of two numbers (so you want to filter on value[1], not value). And because you have a list of one dict rather than just a dict (so you may need to do this for each dict in the list). And of course my filter test isn't the same as yours. But hopefully you can figure it out from here.

abarnert
  • 354,177
  • 51
  • 601
  • 671