Prof. Falken
Prof. Falken

Reputation: 549

Python: Convert One Key Value Pair to String in a Dictionary

I have a function that converts a query into a dictionary that contains a list of dictionaries. Is there an easy way to change just one of the key pairs data types to a string?

My function:

def logs(query):
  client = gcb.Client()
  query_job = client.query(query)
  CSV_COLUMNS ='end_time,device,device_os,device_os_version,latency,megacycles,cost,device_brand,device_family,browser_version,app,ua_parse,key'.split(',')

  ret = {'instances': []}  
  for rows in query_job.result():
    var = list(rows)
    l1 = dict(zip(CSV_COLUMNS,var))
    ret['instances'].append(l1)
  return ret

Which then produces this dictionary:

{'instances': [{'app': u'565',
                'browser_version': u'11.0',
                'cost': u'1.3075e-08',
                'device': u'0',
                'device_brand': u'0',
                'device_family': u'Other',
                'device_os': u'Windows 7',
                'device_os_version': u'0',
                'end_time': u'2018-04-17',
                'key': 1,
                'latency': 0.189589,
                'megacycles': 112.0,
                'ua_parse': u'0'},
               {'app': u'565',
                'browser_version': u'65.0.3325',
                'cost': u'1.3075e-08',
                'device': u'0',
                'device_brand': u'0',
                'device_family': u'Other',
                'device_os': u'Windows 10',
                'device_os_version': u'0',
                'end_time': u'2018-04-16',
                'key': 2,
                'latency': 0.131523,
                'megacycles': 190.0,
                'ua_parse': u'0'}]}

I need to make the 'key' key pair a string. So key':2 needs to be 'key':'2'

I tried this but it just made all data types strings"

def logs(query):
  client = gcb.Client()
  query_job = client.query(query)
  CSV_COLUMNS ='end_time,device,device_os,device_os_version,latency,megacycles,cost,device_brand,device_family,browser_version,app,ua_parse,key'.split(',')

  ret = {'instances': []}  
  for rows in query_job.result():
    var = list(rows)
    l1 = dict(zip(CSV_COLUMNS,var))
    l1.update({str(k):str(v) for k,v in l1.items()})
    ret['instances'].append(l1)
  return ret

Upvotes: 0

Views: 751

Answers (1)

Rieljun Liguid
Rieljun Liguid

Reputation: 1531

You can check the key if is the desired value. A small improvement in your code should suffice:

l1.update({str(k): str(v) if k == 'key' else v for k, v in l1.items()})

Upvotes: 1

Related Questions