Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python json dict iterate {key: value} are the same

i have a json file I am reading in; looks similar to:

[
  {
    "Destination_IP": "8.8.4.4",
    "ID": 0,
    "Packet": 105277
  },
  {
    "Destination_IP": "9.9.4.4",
    "ID": 0,
    "Packet": 105278
  }
]

when i parse the json via:

for json_dict in data:
    for key,value in json_dict.iteritems():
        print("key: {0} | value: {0}".format(key, value))

I am getting:

key: Destination_IP | value: Destination_IP

I have tried using .items() and I have tried just iterating over the keys via iterkeys() and keys() to no avail.

I can call it direct via json_dict['Destination_IP'] and the value returns.

for json_dict in data:
    if 'Destination_IP' in json_dict.keys():
        print json_dict['Destination_IP']

returns:

key: Destination_IP | value: 8.8.4.4

I'm on python 2.7, so any help in running down the value portion would be greatly appreciated.

like image 706
callingconvention Avatar asked Nov 30 '22 00:11

callingconvention


1 Answers

Change your string formats index:

for json_dict in data:
    for key,value in json_dict.iteritems():
        print("key: {0} | value: {1}".format(key, value))

Or without using index:

for json_dict in data:
    for key,value in json_dict.iteritems():
        print("key: {} | value: {}".format(key, value))

Also you can using names instead of index:

for json_dict in data:
    for key,value in json_dict.iteritems():
        print("key: {key} | value: {value}".format(key=key, value=value))

Update: In python3.6 and later, f-string feature added that allow programmers to make formatted string easiest, a f-string work same as template engine that starting by f prefix and string body come after, and variables and other dynamic things must determine between {} signs, same as below:

print(f'key: A | value: {json_dict["A"]}')

>>> key: A | value: X
like image 145
M.javid Avatar answered Dec 23 '22 20:12

M.javid