2

I read a file online and converted it to JSON. I've got the result working but wants to format the numbers (23456876 to a 23,456,875 and 345653 to 345,653)

data_file = [{"name":"python", "downloads":23456876, "version": "3.4.2", "version_downloads": 345653 }]

I wrote the code to get the values but if i use a try except statement inside the for k in key. It wouldn't convert and i also used another way but got cannot convert automatic fields to mamual formatting or something

titles = ["name", "downloads", "version", "Latest downloads"]
key = ["name", "downloads", "version", "version_downloads"]

i = 0
while i < len(data_file):
    results = []
    for k in key: 
        print("{}: {}".format(titles[key.index(k)], data_file[i][k]))
    print()
    i+=1

the result looks like this now:

name: python
downloads: 23456876
latest version: 3.4.2
Latest downloads: 345653

how can i print the downloads to be:

downloads: 2,345,676
Latest downloads: 345653
tushortz
  • 3,697
  • 2
  • 18
  • 31
  • `s= 23456876;print("{:,}".format(s))` – Padraic Cunningham Aug 08 '15 at 22:56
  • @PadraicCunningham i know about this. but my result is in a loop and a combination of different data types. I can't do it to all of them because i only want to format the numbers only – tushortz Aug 08 '15 at 22:58
  • I don't see why is there thing for it in python, you can do just something like n = 45786345; myl = list(n); mod = myl%3; for i in myl: print(i, end = "");if mol ==0: print(",", end == ""); mol=4; mol-=1...... Ok now I get why is there thingie for that :) – Brambor Aug 08 '15 at 23:03

1 Answers1

2

Not sure what you are doing indexing but you can use isinstance to check for ints and doing the formatting if it is:

data_file = [{"name":"python", "downloads":23456876, "version": "3.4.2", "version_downloads": 345653 }]


titles = ["name", "downloads", "version", "Latest downloads"]
key = ["name", "downloads", "version", "version_downloads"]

for  d in data_file:
    for k in key:
        val = d[k]
        if isinstance(val, int):
            val = "{:,}".format(val)
        print("{}: {}".format(titles[key.index(k)], val))

Output:

name: python
downloads: 23,456,876
version: 3.4.2
Latest downloads: 345,653

Instead of indexing I would use a dict to map the names and do lookups:

titles = ["name", "downloads", "version", "Latest downloads"]
key = ["name", "downloads", "version", "version_downloads"]
match = dict(zip(key,titles))
for  d in data_file:
    for k in key:
        val = d[k]
        if isinstance(val, int):
            val = "{:,}".format(val)
        print("{}: {}".format(match[k], val))

Output:

name: python
downloads: 23,456,876
version: 3.4.2
Latest downloads: 345,653

If the only difference is "version_downloads" it may be simpler just to check with an if.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321