Ask Question
3 May, 17:59

We have provided a list of tuples called state_capitals. The first item in every tuple is the name of a US state and the second item in that tuple is the capital of that state. Write code that converts this data structure into a dictionary where the keys are state names and the values are state capitals. Assign the result to the variables capitals_dict. state_capitals = [ ('Michigan', 'Lansing'), ('Massachusetts', 'Boston'), ('Pennsylvania', 'Harrisburg'), ('New York', 'Albany') ]

+2
Answers (1)
  1. 3 May, 18:44
    0
    The solution code is written in Python:

    state_capitals = [ ('Michigan', 'Lansing'), ('Massachusetts', 'Boston'), ('Pennsylvania', 'Harrisburg'), ('New York', 'Albany') ] capitals_dict = {} for x in state_capitals: capitals_dict[x[0]] = x[1] print (capitals_dict)

    Explanation:

    Firstly, we create a variable capitals_dict and initialize it with a empty dictionary (Line 3).

    Next, we use the for-loop to traverse through each tuple item in the state_capitals list (Line 5). Within the loop, we use the syntax x[0] to take out the first item (state) from the tuple and use it as the key capitals_dict[x[0]]. We use the syntax x[1] to take out the second item (capital) from the tuple and set it as the value of the dictionary (capitals_dict[x[0]].). (Line 6)

    When finishing the loop, we can print the dictionary (Line 7) and the output is as follows:

    {'Michigan': 'Lansing', 'Massachusetts': 'Boston', 'Pennsylvania': 'Harrisburg', 'New York': 'Albany'}
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “We have provided a list of tuples called state_capitals. The first item in every tuple is the name of a US state and the second item in ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers