0

I have a json document (as_stats.json) that looks something like this:

{"failed":5, "received": {"192.168.5.2": 40, "192.168.5.45": 84, "127.0.0.1": 145}}

My python code looks like this:

import json,urllib
data = open('as_stats.json').read()
d = json.loads(data)

for x in d['received']:
    if (x != '127.0.0.1'):
        print x

The values returned are the IP addresses, which are variables i.e. the could change any time to any other address. What I am interested in is the number of files received from each IP address as well. When I try rewriting my code as

for x,y in d['received']:
        if (x <> '127.0.0.1'):
            print x,y

I get a message saying "too many values to unpack".

How do I go about getting the values that I want from the key-value pairs?

2
  • 1
    That's severely invalid JSON. Commented Aug 6, 2012 at 16:38
  • 1
    Use != to compare inequality. The <> syntax is obsolete. Commented Aug 6, 2012 at 17:25

1 Answer 1

4

Use:

for x,y in d['received'].iteritems():

Normal iteration over a dict will give you only the keys. Use itervalues to get the values, or iteritems to get both keys and values.

Sign up to request clarification or add additional context in comments.

2 Comments

Or you can do for x in d['received']: print x, d['received'][x] or still for x,y in d['received'].items(): print x,y. It is worth noting that iteritems() returns an iterator, while items() returns a list of tuples.
Thanks kind people. I have made the JSON valid, although that wasn't the problem, minitech and used the more up-to-date operand Colin. Thanks again @interjay. I'm doing python for the first time and it's been ages since I last did some coding :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.