简体   繁体   English

如何从 csv 文件制作特定格式的字典?

[英]How do I make a specifically formatted dictionary from a csv file?

I've looked around on the internet but I haven't found anything that works.我在互联网上环顾四周,但没有找到任何有效的方法。 I want to turn dovah.csv into a dictionary for a translator.我想把dovah.csv变成一个翻译字典。

Is there a way to specifically format it like this?有没有办法像这样专门格式化它?

english_to_dovahzul = {
  'the': 'faal',
  'quick': 'nel',
  'brown': 'prun',
  'fox': 'ilit'
}

dovahzul_to_english = {v: k for k, v in.english_to_dovahzul.items()}

You can try any example from below two:您可以尝试以下两个示例中的任何示例:

example 1: with file handling:示例 1:使用文件处理:

with open(filename) as stream:
    result={}
    for item in stream.readlines()[1:]:
        line = item.strip().split()
        result.update({line[0]:line[2]})    #line[i] is column index to create dict
print(result)

example 2: with pandas.示例 2:使用熊猫。

import pandas as pd
df = pd.read_csv(filename, sep='\t', lineterminator='\r')
result = dict(zip(df["English Word"],df["Dragon Translation"]))  #df['column_name'] is column name to create dict
print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从CSV创建特定格式的JSON文件 - Creating a specifically formatted JSON file from a CSV 如何计算格式非常明确的文件中的对象/子字符串? - How do I count objects/substrings in a very specifically formatted file? 如何使用来自其他字典的键和来自 Python 中的 csv 文件的值制作字典? - How do I make a dictionary with keys from a other dictionary and values from a csv file in Python? 如何从 .t​​xt 文件制作 Python 字典? - How do I make a Python dictionary from .txt file? 从特定格式的文本文件中获取 x 和 y 坐标到 python 中的有序字典中 - Get x and y coordinates from a specifically formatted text file into an Ordered dictionary in python 如何确保我从CSV读取的所有项目都解析为字典? - How do I make sure that all of the items that I read from a CSV are parsed into a dictionary? 如何从 Python 中的 CSV 文件制作图形/图表? - How do i make a graph/diagram from a CSV file in Python? 如何制作带有标头的csv python字典? - How do I make one python dictionary to csv with headers? 如何从 CSV 制作字典键? - How do you make a dictionary key from a CSV? 如何从字典值中删除[]和'',以便可以在csv文件中正确打印 - How do I remove [ ] and ' ' from my dictionary values so that I can print it properly in a csv file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM