[英]How to read 2 different text files line by line and make another file containing a dictionary using python?
I have two text files name weburl.txt and imageurl.txt , weburl.txt contain URLs of website and imageurl.txt contain all images URLs I want to create a dictionary that read a line of weburl.txt and make key of a dictionary and imageurl.txt line as a value. 我有两个文本文件,分别为weburl.txt和imageurl.txt , weburl.txt包含网站的URL, imageurl.txt包含所有图像的URL我想创建一个字典,该字典读取一行weburl.txt并制作字典的关键字, imageurl.txt行作为值。 weburl.txt
weburl.txt
url1
url2
url3
url4
url5......
imageurl.txt imageurl.txt
imgurl1
imgurl2
imgurl3
imgurl4
imgurl5
required output is 所需的输出是
{'url1': imgurl1, 'url2': imgurl2, 'url3': imgurl3......}
I am using this code 我正在使用此代码
with open('weburl.txt') as f :
key = f.readlines()
with open('imageurl.txt') as g:
value = g.readlines()
dict[key] = [value]
print dict
I am not getting the required results 我没有得到所需的结果
you can write something like 你可以写类似
with open('weburl.txt') as f, \
open('imageurl.txt') as g:
# we use `str.strip` method
# to remove newline characters
keys = (line.strip() for line in f)
values = (line.strip() for line in g)
result = dict(zip(keys, values))
print(result)
There are problems with the statement dict[key] = [value]
on so many levels that I get a kind of vertigo as we drill down through them: 语句
dict[key] = [value]
在很多级别上都有问题,当我们深入研究它们时,我会得到一种眩晕感:
dict
(a bad idea because it would overshadow Python's builtin reference to the dict
class). dict
的变量(一个坏主意,因为它会使Python对dict
类的内置引用盖过阴影)。 Let's call it d
instead. d
。 d
this oversight would earn you an easy-to-understand NameError
. d
这种疏忽将使您容易理解NameError
。 However since you're calling it dict
, Python will actually be attempting to set items in the dict
class itself (which doesn't support __setitem__
) instead of inside a dict
instance, so you'll get a different, more-confusing error. dict
,因此Python实际上将尝试在dict
类本身(不支持__setitem__
)中设置项目,而不是在dict
实例内部进行设置,因此您将得到另一个更混乱的错误。 dict
entry assignment where the key is a non-hashable type ( key
is a list
). dict
条目分配,其中键是不可哈希的类型( key
是list
)。 You could convert the list
to the hashable type tuple
easily enough, but that's not what you want because you'd still be... list
转换为可哈希类型的tuple
,但这不是您想要的,因为您仍然会... d[key] = value
syntax. d[key] = value
语法无法做到这一点。 It could be done all in one relatively simple statement, ie d=dict(zip(key,value))
but unfortunately that doesn't get around the fact that you're... d=dict(zip(key,value))
但不幸的是,这并不能解决您正在... Instead, this line: 相反,此行:
d = dict((k.strip(), v.strip()) for k, v in zip(key, value))
will do what you appear to want. 将执行您想要的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.