Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: create dict from list and auto-gen/increment the keys (list is the actual key values)?

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

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

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

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
like image 479
jed Avatar asked Nov 02 '11 01:11

jed


People also ask

Can you increment a value in a dictionary Python?

By using the get() function we can increment a dictionary value and this method takes the key value as a parameter and it will check the condition if the key does not contain in the dictionary it will return the default value. If the given key exists in a dictionary then it will always return the value of the key.

Can Python dictionary have list as keys?

We can use integer, string, tuples as dictionary keys but cannot use list as a key of it .

Does dict values () return a list?

The methods dict. keys() and dict. values() return lists of the keys or values explicitly.

Can a dict have a list as value?

It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.


1 Answers

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))
like image 188
Karl Knechtel Avatar answered Sep 23 '22 14:09

Karl Knechtel