12 Days of Baddass Courses sale! Get instant access to the entire egghead library of courses and lessons for 58% off.

Runs out in:
15 : 06 : 05 : 24
Become a member
to unlock all features

    Turning a key/value string into a dictionary in Python

    Chris BiscardiChris Biscardi

    Sometimes you get strings instead of objects and you have to parse them out. Here's an example where the raw data I got from a Twitch chatbot message wasn't useful to me until I parsed it into a dictionary.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Chris Biscardi: Let's start by opening a Python ripple. Next we'll assign the variable raw data to our string. I happen to get this string from a Twitch bot. Note that there are key value pairs, nothing is quoted and all the key value pairs were separated by a semicolon. First, we'll want to split the string on the semicolon.

    Next, for each item in the resulting list, we want to split on the equal sign. Finally, we want to construct a dictionary. We'll also set the result to items. Note that items is now a dictionary. Because items is a dictionary, we can now get any key in that dictionary. Here it seems that the subscriber value is a one wrapped in a string. We would want to deal with that if we cared about this value.

    Here's the username that sent the message.