I have a really weird python problem. I have already asked several colleagues who all had no idea how it happened and how it could be solved.
I have a shallow dict of strings that I receive from an API call and I want to assign some of those values to a new dict.
This is what the first dict looks like. Just a bunch of strings:
I assign some values from dict1 to some keys in dict2. Really basic
dict2={}
dict2['access_key'] = dict1['access_key']
dict2['secret_access_key'] = dict1['secret_access_key'],
dict2['session_token'] =dict1['session_token'],
dict2['region'] = dict1['region']
Then this happens. The values for "secret access key" and "session_token" are turned into tuples. "access_key" and "region" remain strings
I have already tried initialising the values as strings, accessing the first entry of the tuple and casting the value to a string. All of that did not change anything. It seems like the value is assigned just fine and then something weird happens that turns it into a tuple
This is a screenshot of my Interpreter settings. I am using Pyython 3.6
I am really going crazy over this one :-/ Any help would be greatly appreciated
First, you ask why this is turned into a "tuple" - the answer to that question is because that is what the . items() method on dictionaries returns - a tuple of each key/value pair. Show activity on this post. With a dictionary you can add another variable while iterating over it.
Python dictionary tuples as key To access the tuple elements from the dictionary and contains them in a list. We have to initialize a dictionary and pass the tuple key and value as an argument. Now to get all tuple keys from the dictionary we have to use the Python list comprehension method.
Use the items() Function to Convert a Dictionary to a List of Tuples in Python. The items() function returns a view object with the dictionary's key-value pairs as tuples in a list. We can use it with the list() function to get the final result as a list.
You can easily convert python string to the dictionary by using the inbuilt function of loads of json library of python. Before using this method, you have to import the json library in python using the “import” keyword.
You have trailing commas at the end of two of your calls. This is why the strings are transformed to tuples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With