IP_Engr
IP_Engr

Reputation: 135

Accessing values of a dictionary in a list using lambda

I'm a newbie to python. I've multiple dictionaries inside a list and I want to do some analysis based on values. The reason I'm using lambda is because the function is not always expected. I'm just showing 2 dictionaries for reference, but the output gives me multiple dictionaries at times.

statistics = [{"ip_dst": "10.0.0.1", "ip_proto": "icmp", "ip_src": "10.0.0.3",
               "bytes": 1380, "port_dst": 0, "packets": 30, "port_src": 0},
              {"ip_dst": "10.0.0.3", "ip_proto": "icmp", "ip_src": "10.0.0.1",
               "bytes": 1564, "port_dst": 0, "packets": 34, "port_src": 0}]

packets = filter(lambda x: x[0]["packets"], statistics)
ip_src = filter(lambda x: x[0]["ip_src"], statistics)
ip_proto = filter(lambda x: x[0]["ip_proto"], statistics)

When I'm using a print statement, it's giving me a Key Error: 0. I understand that the value of packets is an integer and for ip_src/ip_proto, the value is a string.

How to access these values using lambdas?

Upvotes: 2

Views: 16758

Answers (3)

OneCricketeer
OneCricketeer

Reputation: 191758

The filter function returns the original list without the elements where the lambda evaluates to false. So, if you did that correctly, you'd get all the elements anyways because a non-empty string or value other than 0 is considered to be True in Python.

If you'd like to get just those values of the keys, you need list comprehension.

packets = list(x["packets"] for x in statistics)

Upvotes: 0

Andy G
Andy G

Reputation: 19367

If you are trying to extract the packets as a separate list of items then you wouldn't use filter. Filter will just reduce the number of dictionaries in a new list. You could use a list comprehension,

packets = [x['packets'] for x in statistics]
print(packets)
# [30, 34]

This creates a list of the x['packets'] values in statistics.

The same for the other two sets of values.

Upvotes: 2

DeepSpace
DeepSpace

Reputation: 81644

You don't need [0].

When using filter(lambda x: ...), x is the element in the iterable. Since you have a list of dictionaries, x will be the dictionary itself.

Your code should be:

statistics = [{"ip_dst": "10.0.0.1", "ip_proto": "icmp", "ip_src": "10.0.0.3", "bytes": 1380, "port_dst": 0, "packets": 30, "port_src": 0}, {"ip_dst": "10.0.0.3", "ip_proto": "icmp", "ip_src": "10.0.0.1", "bytes": 1564, "port_dst": 0, "packets": 34, "port_src": 0}]


packets = filter(lambda x: x["packets"], statistics)
ip_src = filter(lambda x: x["ip_src"], statistics)
ip_proto = filter(lambda x: x["ip_proto"], statistics)

Upvotes: 1

Related Questions