Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8037925
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T03:04:14+00:00 2026-06-05T03:04:14+00:00

I am trying to create a dictionary from a list and tuple of tuples

  • 0

I am trying to create a dictionary from a list and tuple of tuples as illustrated below. I have to reverse map the tuples to the list and create a set of non-None column names.

Any suggestions on a pythonic way to achieve the solution (desired dictionary) is much appreciated.

MySQL table ‘StateLog’:

Name NY   TX   NJ
Amy  1    None 1
Kat  None 1    1
Leo  None None 1

Python code :

## Fetching data from MySQL table
#cursor.execute("select * from statelog")
#mydataset = cursor.fetchall()
## Fetching column names for mapping
#state_cols = [fieldname[0] for fieldname in cursor.description]

state_cols = ['Name', 'NY', 'TX', 'NJ']
mydataset = (('Amy', '1', None, '1'), ('Kat', None, '1', '1'), ('Leo', None, None, '1'))

temp = [zip(state_cols, each) for each in mydataset]

# Looks like I can't do a tuple comprehension for the following snippet : finallist = ((eachone[1], eachone[0]) for each in temp for eachone in each if eachone[1] if eachone[0] == 'Name')
for each in temp:
    for eachone in each:
        if eachone[1]:
            if eachone[0] == 'Name':
                k = eachone[1]
            print k, eachone[0]

print '''How do I get a dictionary in this format'''            
print '''name_state = {"Amy": set(["NY", "NJ"]),
                "Kat": set(["TX", "NJ"]),
                "Leo": set(["NJ"])}'''

Output so far :

Amy Name
Amy NY
Amy NJ
Kat Name
Kat TX
Kat NJ
Leo Name
Leo NJ

Desired dictionary :

name_state = {"Amy": set(["NY", "NJ"]),
              "Kat": set(["TX", "NJ"]),
              "Leo": set(["NJ"])}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T03:04:15+00:00Added an answer on June 5, 2026 at 3:04 am

    To be really honest, I would say your problem is that your code is becoming too cumbersome. Resist the temptation of “one-lining” it and create a function. Everything will become way easier!

    mydataset = (
            ('Amy', '1', None, '1'),
            ('Kat', None, '1', '1'),
            ('Leo', None, None, '1')
    )
    
    def states(cols, data):
        """
        This function receives one of the tuples with data and returns a pair
        where the first element is the name from the tuple, and the second
        element is a set with all matched states. Well, at least *I* think
        it is more readable :)
        """
        name = data[0]
        states = set(state for state, value in zip(cols, data) if value == '1')
        return name, states
    
    pairs = (states(state_cols, data) for data in mydataset)
    # Since dicts can receive an iterator which yields pairs where the first one
    # will become a key and the second one will become the value, I just pass
    # a list with all pairs to the dict constructor.
    print dict(pairs)
    

    The result is:

    {'Amy': set(['NY', 'NJ']), 'Leo': set(['NJ']), 'Kat': set(['NJ', 'TX'])}
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to create a dictionary from 2 lists where one list contains
I am trying to create a Python dictionary from a stored list. This first
Alright well I am trying to create a dictionary from a text file so
I'm trying to create a .resx file from a dictionary of strings. Luckily the
I'm trying to create a dictionary of words from a collection of files. Is
I'm trying to use LINQ to create a new dictionary from an existing one,
I am trying to create a dictionary from a relatively large numpy array. I
I'm trying to create a dictionary type - ie hash table with a string
I'm trying to create a Dictionary with array of integer, string and boolean data
I was trying to create a generic Dictionary that implements IXmlSerializable (credit to Charles

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.