Can someone explain how to add a file to a dictionary.
The file is simple. Maybe a word or a number on each line.
Here is the code I have. Didn't know if i should use this post or the List and Dictionaries post so kind of posted twice... sorry

import random

def main():
    ##Open a file
    outfile = open('numbers.txt', 'w')
    for count in range(20):
        ##Get random numbers
        rebmun = random.randint(1,99)
        outfile.write(str(rebmun) + '\n')
    outfile.close()
    text = open('numbers.txt','r').read()
    muns = text.split()
    
    numbers = {}
    for ch in muns:
        numbers[ch] = numbers.values()
        print numbers
main()

Do not run the program I get an unusually long output.

What do you expect this dictionary to look like?
Let's say muns =

Try Exercising with this :)

def MakeDict(dict_name):
    dict_name = dict()
    return dict_name


def AddName(Name, key_name, dict_name):
    dict_name[key_name] = Name
    print "Added " + str(Name)+ "at " +str(key_name)
    
#now we will use our dictionary
#create dictionary
mydict = MakeDict("evstevemd")
print mydict

#Add some stuffs in dictionary
AddName("Boo! Boo!", "calf", mydict)
print mydict

Do you mean something like that?

import random

def main():
    ##Open a file
    outfile = open('numbers.txt', 'w')
    for count in range(10):
        ##Get random numbers
        rebmun = random.randint(1,99)
        outfile.write(str(rebmun) + '\n')
    outfile.close()

    # read the file you just created
    text = open('numbers.txt','r').read()
    num_list = text.split()
    
    # create a dictionary with ix:val pairs
    num_dict = {}
    for ix, val in enumerate(num_list):
        # test only
        print( ix, val)
        num_dict[ix] = int(val)
        
    # test result
    print('-'*70)
    print(num_dict)

main()

"""
my output -->
(0, '98')
(1, '51')
(2, '97')
(3, '60')
(4, '29')
(5, '23')
(6, '65')
(7, '1')
(8, '56')
(9, '56')
----------------------------------------------------------------------
{0: 98, 1: 51, 2: 97, 3: 60, 4: 29, 5: 23, 6: 65, 7: 1, 8: 56, 9: 56}

"""

How do I go about finding duplicates in a dictionary. My code is still messy but I started using compare to try and find the duplicate.

It is more common to iterate the file one record at a time instead of the read() and split().

import random

outfile = open('numbers.txt', 'w')
for count in range(20):
        ##Get random numbers
        rebmun = random.randint(1,99)
        outfile.write(str(rebmun) + '\n')
outfile.close()

numbers={}
fp = open('numbers.txt','r')
for rec in fp:
        numbers[rec.strip()] = "test"
print numbers
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.