如何遍历这本字典而不是对键进行硬编码 [英] How can I loop through this dictionary instead of hardcoding the keys

查看:35
本文介绍了如何遍历这本字典而不是对键进行硬编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我有这个代码(来自 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

这篇关于如何遍历这本字典而不是对键进行硬编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆