python - Print out dictionary from file
问题描述
E;Z;X;Y
I tried
dl= defaultdict(list)
for line in file:
line = line.strip().split(';')
for x in line:
dl[line[0]].append(line[1:4])
dl=dict(dl)
print (votep)
It print out too many results. I have an init that reads the file.
What ways can I edit to make it work?
解决方案
The csv
module could be really handy here, just use a semicolon as your delimiter and a simple dict comprehension will suffice:
with open('filename.txt') as file:
reader = csv.reader(file, delimiter=';')
votep = {k: vals for k, *vals in reader}
print(votep)
Without using csv
you can just use str.split
:
with open('filename.txt') as file:
votep = {k: vals for k, *vals in (s.split(';') for s in file)}
print(votep)
Further simplified without the comprehension this would look as follows:
votep = {}
for line in file:
key, *vals = line.split(';')
votep[key] = vals
And FYI, key, *vals = line.strip(';')
is just multiple variable assignment coupled with iterable unpacking. The star just means put whatever’s left in the iterable into vals after assigning the first value to key.
推荐阅读
- botframework - 带有自适应卡的机器人框架编写器上的拇指向上/向下满意度表情符号 UI
- java - 发送到服务器时 Proguard 更改字符串请求变量名称
- string - 传递 `&str` 对 Rust 的性能不是很不利吗?
- python - Django如何使用切片查询集获得一个结果
- java - 在 Liferay 6.2 (Localhost) 中的 cookie 中放入安全和 httponly 标志
- c# - TPL Dataflow 模块可从单个输入生成多个输出
- java - Spring Cloud Gateway中如何实现Redis Rate Limiting?
- oracle - 如何使用所有列作为属性和行作为命名的 XML 标记生成 XML
- android - 使用 Android 内容提供程序 MediaStore.Files.getContentUri(VOLUME_NAME_EXTERNAL) 删除物理文件
- python - 使用 pd.to_datetime Python 将数据集中的列从 UTC 转换为日期时间