How can I loop through this dictionary instead of hardcoding the keys(如何遍历这本字典而不是对键进行硬编码)
问题描述
到目前为止,我有这个代码(来自 cs50/pset6/DNA):
So far, I have this code (from cs50/pset6/DNA):
import csv
data_dict = {}
with open(argv[1]) as data_file:
    reader = csv.DictReader(data_file)
    for record in reader:
        # `record` is a dictionary of column-name & value
        name = record["name"]
        data = {
            "AGATC": record["AGATC"],
            "AATG": record["AATG"],
            "TATC": record["TATC"],
        }
        data_dict[name] = data
print(data_dict)
输出
{'Alice': {'AATG': '8', 'AGATC': '2', 'TATC': '3'},
     'Bob': {'AATG': '1', 'AGATC': '4', 'TATC': '5'},
 'Charlie': {'AATG': '2', 'AGATC': '3', 'TATC': '5'}}
这里是 csv 文件:
Here is the csv file:
name,AGATC,AATG,TATC
Alice,2,8,3
Bob,4,1,5
Charlie,3,2,5
但我的目标是实现完全相同的目标,而不是对键 AATG 等进行硬编码,而且因为我将使用包含更多值的更大的数据库,我希望能够遍历数据,而不是这样做:
But my goal is to achieve the exact same thing, but instead of hardcoding the keys AATG, etc., and also because I'll use a much much bigger database that contains more values, I want to be able to loop through the data, instead of doing this:
data = {
            "AGATC": record["AGATC"],
            "AATG": record["AATG"],
            "TATC": record["TATC"],
        }
你能帮我吗?谢谢
推荐答案
您也可以尝试使用 Pandas.
You could also try using pandas.
使用您的示例数据作为 .csv 文件:
Using your example data as .csv file:
pandas.read_csv('example.csv', index_col = 0).transpose().to_dict()
输出:
{'Alice': {'AGATC': 2, 'AATG': 8, 'TATC': 3},
 'Bob': {'AGATC': 4, 'AATG': 1, 'TATC': 5},
 'Charlie': {'AGATC': 3, 'AATG': 2, 'TATC': 5}}
index_col = 0 因为你有我设置为索引的名称列(以便以后成为字典中的顶级键)
index_col = 0 because you have names column which I set as index (so that later becomes top level keys in dictionary)
.transpose() 所以顶级键是名称而不是特征(AGATC、AATG 等)
.transpose() so top level keys are names and not features (AGATC, AATG, etc.)
.to_dict() 将 pandas.DataFrame 转换为 python 字典
.to_dict() to transform pandas.DataFrame to python dictionary
这篇关于如何遍历这本字典而不是对键进行硬编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何遍历这本字典而不是对键进行硬编码
				
        
 
            
        - ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
 - 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
 - YouTube API v3 返回截断的观看记录 2022-01-01
 - 如何使用PYSPARK从Spark获得批次行 2022-01-01
 - CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
 - 我如何卸载 PyTorch? 2022-01-01
 - 使用 Cython 将 Python 链接到共享库 2022-01-01
 - 我如何透明地重定向一个Python导入? 2022-01-01
 - 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
 - 计算测试数量的Python单元测试 2022-01-01
 
