Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to split strings into dictionaries in Python

Shulou Source: shulou.com Published: 2022-06-02 05:50:37 10月04日 Update

In this issue, the editor will bring you about how to split strings into the dictionary in Python. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

1.1 split strings into dictionaries

#! / 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)

Output quantity

Key1 value1key2 value2key3 value3

1.2 convert two lists into dictionaries

#! / 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)

Output quantity

Key1 value1key2 value2key3 value3

1.3 zip example

#! / usr/bin/pythonstr1 = "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)

Output quantity

Key1 value1key2 value2key3 value3

The above is how to split the string into the dictionary in the Python shared by the editor. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Tags: Dictionary character string output content analysis professional two small and medium rich in content that is articles more knowledge examples articles industry perspective information information channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Apple vpn Xiaomi Redmi