将两个JSON {key1:value1,key2:value2}组合到单个键(i e {key3:value1,value2})Python

时间:2016-05-04 06:54:27

标签: python json

我想将经度和纬度结合起来 {latlon:'40 .33333,-79.34343'}

整个JSON位于变量data = jsonData

我想删除原始键值对

{
  'locale': 'en_US',
  'timezone': '-7',
  'id': '13',
  'agerangemin': '21',
  'verified': 'true',
  'coverimageurl': 'scontent.xx.fbcdn/t31.0-0/p480x480/13063482_1183967848280764_1411489384515766669_o.jpg',
  'tagline': 'Veggien',
  'lastupdated': '1462341401',
  'fbupdated_time': '2016-03-30T00:38:48+0000',
  'lname': 'Kulkarni',
  'fname': 'Nikhil',
  'email': 'nikhilhk.usa@gmail.com',
  'latitude': '40.333333',
  'longitude': '-79.34343',
  'displayname': 'Nikhil Kulkarni',
  'fbprofileid': '1121344884543061',
  'profileimageurl': 'scontent.xx.fbcdn/hprofile-xft1/v/t1.0-1/p100x100/10423743_952350738109144_964810479230145631_n.jpg?oh=71f7e953dbbf8e2f1d9f22418f7888b2&oe=579F4A36',
  'link': 'facebook/app_scoped_user_id/1121344884543061/',
  'diet': 'Vegetarian',
  'dietsinceyear': '1966',
  'gender': 'M',
  'vegstory': '',
  'shortdescription': 'Just like that',
  'categoryids': '',
  'reasonforveg': 'Religious'
}

3 个答案:

答案 0 :(得分:0)

>>> json_data['latlon'] = ','.join(json_data[k] for k in ('latitude', 'longitude'))
>>> json_data['latlon']
'40.333333,-79.34343'

请注意,这将保留原始键值对。

<强>更新

如果要删除原始键值对,请使用pop方法:

>>> json_data['latlon'] = ','.join(json_data.pop(k) for k in ('latitude', 'longitude'))
>>> json_data['latlon']
'40.333333,-79.34343'

答案 1 :(得分:0)

data['latlong'] = data['latitude'] + ',' + data['longitude']
del data['latitude']
del data['longitude']

答案 2 :(得分:0)

可以在一行中完成。

>>> dic = {'latitude': '40.333333', 'longitude': '-79.34343'}
>>>
>>> dic['latlon'] = "{0},{1}".format(dic.pop('latitude'),dic.pop('longitude'))
>>> dic
{'latlon': '40.333333,-79.34343'}

要了解dic.pop()的工作原理,请参阅this.