En este tutorial te damos algunos ejemplos de cómo dividir un string en un dict en Python.
1Dividir un string en un dict
#!/usr/bin/python str = "key1=value1;key2=value2;key3=value3" d = dict(x.split("=") for x in str.split(";")) for k, v in d.items(): print(k, v)
Salida:
key1 value1 key2 value2 key3 value3
2Convertir dos listas en un dict
#!/usr/bin/python str1 = "key1 | key2 | key3" str2 = "value1 | value2 | value3" keys = str1.split("|") values = str2.split("|") d = {} for k in keys: k = k.strip() # key trim for v in values: d[k] = v.strip() # value trim for k, v in d.items(): print(k, v)
Salida:
key1 value1 key2 value2 key3 value3
3Usando zip
#!/usr/bin/python str1 = "key1 | key2 | key3" str2 = "value1 | value2 | value3" keys = str1.split(" | ") values = str2.split(" | ") d = dict(zip(keys, values)) for k, v in d.items(): print(k, v)
Salida:
key1 value1 key2 value2 key3 value3