简体   繁体   中英

Python how to check the dictonary have value in list and change to string type?

I have below dictionary in which value for some of keys are appeared as list. i need to find those values which are list type and need to convert to string


details=
{
  "dsply_nm": [
    "1981 test test"
  ],
  "eff_dt": [
    "2021-04-21T00:01:00-04:00"
  ],
  
  "exp_dt": [
    "2022-04-21T00:01:00-04:00"
  ],
  "pwr": [
    "14"
  ],
  "is_excl": [
    "true"
  ],
  
  "is_incl": [
    "false"
  ],
  
  "len": [
    "14"
  ],
  "max_spd": [
    "14"
  ],
  "id": "58",
  "type_nm": "single",
  "updt_dttm": "2021-04-21T13:40:11.148-04:00",
  "nbr": "3",
  "typ": "premium",
  "nm": "test"
}

below code not seems to be working and its not returning as string

test={}
for k,v in details.items():
    if isinstance(v, list):
        test[k]="".join(str(v))
    test[k]=v
print(test)

expected should be as below

{'dsply_nm':'1981 test test', 
"eff_dt": "2021-04-21T00:01:00-04:00", 
"exp_dt":"2022-04-21T00:01:00-04:00",
"pwr":"14",
"is_excl":"true",
"is_incl": "false",
"len":"14",
"max_spd":"14",
"id":"58",
"updt_dttm":"2021-04-21T13:40:11.148-04:00",
"nbr":"3",
"typ": "premium",
"nm":"test"
}

anybody can help on this?

Your code is almost correct - you forgot else clause and should not use str(v) before join . This code works fine:

test={}
for k,v in details.items():
    if isinstance(v, list):
        test[k]="".join(v)
    else:
        test[k]=v
print(test)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM