Python:从列表创建dict,并自动生成/增加密钥(列表是实际的键值)? [英] Python: create dict from list and auto-gen/increment the keys (list is the actual key values)?

查看:231
本文介绍了Python:从列表创建dict,并自动生成/增加密钥(列表是实际的键值)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经很努力地搜索,找不到与我想要的完全一致的问题。

i've searched pretty hard and cant find a question that exactly pertains to what i want to..

我有一个名为 1000行随机AZ排序词...

I have a file called "words" that has about 1000 lines of random A-Z sorted words...

10th
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
a
AAA
AAAS
Aarhus
Aaron
AAU
ABA
Ababa
aback
abacus
abalone
abandon
abase
abash
abate
abater
abbas
abbe
abbey
abbot
Abbott
abbreviate
abc
abdicate
abdomen
abdominal
abduct
Abe
abed
Abel
Abelian

我正在尝试将该文件加载到字典中,其中使用该字是键值,并且键实际上是自动生成/自动递增每个单词

I am trying to load this file into a dictionary, where using the word are the key values and the keys are actually auto-gen/auto-incremented for each word

例如{0:10,1:1,2:2nd} ... etc..etc ...

e.g {0:10th, 1:1st, 2:2nd} ...etc..etc...

以下是到目前为止,我一直在玩的代码,似乎是排序的作品,但它只显示了文件中最后一个条目作为唯一的dict对元素

below is the code i've hobbled together so far, it seems to sort of works but its only showing me the last entry in the file as the only dict pair element

f3data = open('words')

mydict = {}

for line in f3data:
    print line.strip()
    cmyline = line.split()
    key = +1
    mydict [key] = cmyline

print mydict


推荐答案

key = +1

+1 1 相同。我假设你的意思是 key + = 1 。每行只有一个项目时,我也看不出每个行的分割的原因。

+1 is the same thing as 1. I assume you meant key += 1. I also can't see a reason why you'd split each line when there's only one item per line.

但是,真的没有理由自己做循环。

However, there's really no reason to do the looping yourself.

with open('words') as f3data:
    mydict = dict(enumerate(line.strip() for line in f3data))

这篇关于Python:从列表创建dict,并自动生成/增加密钥(列表是实际的键值)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆