Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将两列转换为Python字典的最简单方法_Python - Fatal编程技术网

将两列转换为Python字典的最简单方法

将两列转换为Python字典的最简单方法,python,Python,如何将以下信息放入Python字典--?键将是国家,值将是两个字符的ISO代码 例如,我希望结果是: mapping_of_country_to_iso = {'AALAND ISLANDS':'AX','AFGHANISTAN':'AF',...} 如果你是python2.7+,你可以使用字典理解 {k:v for k,v in list_of_tuples} 其中元组的每个成员的形式为(“AALAND ISLANDS”、“AX”)。这是更通用的解决方案,但对于您的场景可能不是必需的 对

如何将以下信息放入Python字典--?键将是国家,值将是两个字符的ISO代码

例如,我希望结果是:

mapping_of_country_to_iso = {'AALAND ISLANDS':'AX','AFGHANISTAN':'AF',...} 

如果你是python2.7+,你可以使用字典理解

{k:v for k,v in list_of_tuples}
其中元组的每个成员的形式为
(“AALAND ISLANDS”、“AX”)
。这是更通用的解决方案,但对于您的场景可能不是必需的

对于较旧的python,您可以简单地调用字典构造函数,并将元组列表作为参数

dict(list_of_tuples)

你会得到你想要的

我只是将重要数据复制并粘贴到一个名为“countries.txt”的文本文件中,然后执行如下操作:

import string

myFilename = "countries.txt"

myTuples = []


myFile = open (myFilename, 'r')

for line in myFile.readlines():
    splitLine = string.split (line)
    code = splitLine [-3]
    country = string.join(splitLine[:-3])
    myTuples.append(tuple([country, code]))

myDict = dict(myTuples)
print myDict
这可能不是做这件事的“最佳”方式,但似乎有效

以下是John Machin的有益建议:

import string

myFilename = "countries.txt"


myDict = {}

myFile = open (myFilename, 'r')

for line in myFile:
    splitLine = string.split (line)
    code = splitLine [-3]
    country = " ".join(splitLine[:-3])
    myDict[country] = code

print myDict

如果我正确理解您的问题,我相信
df.to_dict()
函数将非常有用

假设国家信息的数据框架称为df,首先(如果还没有),将“国家”设置为索引。接下来,使用
.to_dict()
函数。下面是代码的外观:

df = df.set_index('Country')
dict = df.to_dict('series')

“系列”
只是组织词典的方法之一。我建议您查看pandas文档,因为有几种方法可以使用此命令。

如何获取元组?这是一种非常棒/简单的方法。Python的字符串功能非常强大。我只是将它粘贴到解释器中。我一直在使用小数据集:)
data=''
+paste+
'
-是的,功能非常强大。(1)您不需要
读线
<代码>对于myFile中的行:就足够了。(2)
元组([country,code])
可以简化为
(country,code)
。(3)更好地将它们直接重写到DICT中:最初是代码> MyDICT= {} <代码>,然后<代码> MyDiT[WORK] =代码每次循环(4)考虑使用<代码>事物< /代码>,而不是<代码> MyTys< /代码>。HTH.(5)除非您的目标是Python1.x,否则请使用
“”.join(seq)
而不是
string.join(seq)
。。。
string
模块中的大多数函数都不推荐使用
str
方法。