开发者

Loading a python dictionary with variables

How do i load a text file full of 10 digit codes separated by a return into a dictionary in python? Then how do i cross check the variables in the dictionary with my own variables?

Ok, it is simple really. I have a TXT file containing 1000 or so 10 digit sequences looks like this:

121001000

000000000

121212121

I need to input these files into a dictionary then be able to take a number that i receive and cross check it with this datab开发者_StackOverflow中文版ase so it does NOT match. IE 0000000001 =/= any previous entry.


It sounds like you want to store the numbers in a way that makes it easy to look up "Is this other value already there?", but you don't actually have "values" to associate with these "keys" - so you don't really want a dict (associative array), but rather a set.

Python file objects are iterable, and iterating over them gives you each line of the file in turn. Meanwhile, Python's container types (including set) can be constructed from iterables. So making a set of the lines in the file is as simple as set(the_file_object). And since this is Python, checking if some other value is in the set is as simple as some_other_value in the_set.


On reading text from files, try looking over the python document for input/output. Additionally look through data structures tutorial. Dictionary usually has a key and a value, that corresponds to the key:

name: "John"
age: 13

If you are just looking for the structure to read the values from the file, list seems to be more appropriate, since you did not specify anything about the designation of those values.


If you need the file's contents as numbers and not as strings:

file_data = set()
for line in open('/some/file/with/sequences.txt'):
    file_data.add(int(line))

then later:

if some_num not in file_data:
    do_something_with(some_num)

If you have blank lines or garbage in the file, you'll want to add some error checking.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜