给定的key-pair元组,我需要创建一个字典 [英] With given key-pair tuples, I need to create a dictionary
本文介绍了给定的key-pair元组,我需要创建一个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用my_file.txt中的key-pair元组,创建一个字典。如果密钥存在多个不同的值,请使用第一个看到的值
(例如,我们遇到的密钥的第一个实例)。
Using the key-pair tuples from my_file.txt, create a dictionary. If a key exists multiple times with different values, use the first seen value (e.g., the first instance we encountered the key).
my_file = [('a', '1')
('b', '2')
('c', '3')
('d', '4')
('e', '5')]
def makehtml(fname):
with open(fname) as f: # reads lines from a fname file
for line in f:
tups = line2tup(line,"--") # turns each line into a 2 elem tuple on it's own line.
print tups
如何从my_file键/值对中创建一个字典。我试过了dict(my_file),但是告诉我ValueError:dictionary update sequence element#0 has length 1; 2 is required。
How can I create a dictionary from my_file key/value pairs. I've tried dict(my_file), but it's telling me that "ValueError: dictionary update sequence element #0 has length 1; 2 is required".
推荐答案
这样做:
mydict = {}
for line in open(fname):
k, v = line.split()
mydict[int(k)] = v
这篇关于给定的key-pair元组,我需要创建一个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文