list - 如何创建一个字典,将字符串映射到给定列表和元组的集合?

标签 list dictionary tuples python

我正在尝试从列表和元组元组创建字典,如下所示。我必须将元组反向映射到列表并创建一组非 None 列名称。

非常感谢任何关于实现解决方案的Python方式的建议(所需的字典)。

MySQL 表“StateLog”:

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

Python 代码:

## 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"])}'''

到目前为止的输出:

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

所需词典:

name_state = {"Amy": set(["NY", "NJ"]),
              "Kat": set(["TX", "NJ"]),
              "Leo": set(["NJ"])}

最佳答案

说实话,我想说你的问题是你的代码变得太麻烦了。抵制“单行”的诱惑并创建一个功能。一切都会变得更加容易!

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)

结果是:

{'Amy': set(['NY', 'NJ']), 'Leo': set(['NJ']), 'Kat': set(['NJ', 'TX'])}

关于list - 如何创建一个字典,将字符串映射到给定列表和元组的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10853348/

相关文章:

python - 浮点值作为字典键

Python 认为我的列表是一个元组?

python - 将带有 2 层定界符的字符串转换为字典 - python

python - 气泡排序开关和旋转挑战

asp.net-mvc - 在 ASP.NET MVC 中检查 Razor 中的字典键

android - 列出一个 fragment ?

java - 将值存储在 Java 集合中

python - 从元组列表中返回最大值

Python 在列表或数组的范围内查找数字

Java - 使用递归返回列表