The loop appends each key and value pair to a list that the function returns when it's finished. The above function returns a flattened list, and the concept is simple. Print(convertToStraightList(myDictionary)) The following function does it: def convertToStraightList (sampleDict): While the above for loop options produce a nested list, you can destructure it further into a straight list if that's what you want. Return a new view of the dictionary’s items ((key, value) pairs) You will have to do this instead. You can also achieve this using a for loop together with Python’s list comprehension feature: convertedList = ] for i in myDictionary]įunction to Convert a Python Dictionary Into a Flat List You can easily do this: for dictitem in dataList: for key in dictitem: print (dictitem key) It will iterate over the list, and for each dictionary in the list, it will iterate over the keys and print its values. ems returns a tuple of the key value pairs. or if using Python 3 and pip3: pip3 install pyyaml. First off, install the YAML module using pip: pip install pyyaml. It serves the same purpose as the json.dumps () function but in YAML format instead of JSON. The for loop gives you more traction on your data while converting a Python dictionary into a list.įor instance, the following code converts a dictionary into a nested list: myDictionary = ) or parenthesis ( ()) accordingly. Another way to pretty print a dictionary is by using the dump () function of the yaml module. Convert a Python Dictionary Into a List Using a for Loop
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |