2

I have in Python this dictionary:

[('157.55.39.64', 4), ('188.165.15.192', 2), ('1.165.15.192', 1)]

where the first field is an IP adress and the other one represents how many times is present in a file.

I would like to have a json representation of it like this one:

[{"ip":"157.55.39.64","times":4},
  {"ip":"188.165.15.192","times":2},
   {"ip":"1.165.15.192","times":1}]

I tried using jsonify(dictionary), but I get this:

{"157.55.39.64":4, "188.165.15.192": 2, "1.165.15.192":1}

which is only one json item. I don't know either how to put the strings "ip" and "times" in order to appear in the json file.

Any help?

1
  • Your initial structure is a list of tuples. Not a dictionary. Commented Apr 23, 2016 at 12:04

2 Answers 2

5

If your original structure is called ips, you can get json you need with

ips = [('157.55.39.64', 4), ('188.165.15.192', 2), ('1.165.15.192', 1)]
json.dumps([{"ip": ip[0], "times": ip[1]} for ip in ips])

Output will be

[
    {
        "ip": "157.55.39.64",
        "times": 4
    },
    {
        "ip": "188.165.15.192",
        "times": 2
    },
    {
        "ip": "1.165.15.192",
        "times": 1
    }
]
Sign up to request clarification or add additional context in comments.

Comments

0

Use a list comprehension to convert the data into required format and the try jsonify.

data = [('157.55.39.64', 4), ('188.165.15.192', 2), ('1.165.15.192', 1)]
data = [{"ip": ip, "times": times} for ip, times in data]

Now, use jsonify to convert this list into json.

Comments

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.