Home > Software engineering >  ID inserted automatically in a dictionary and write into a file
ID inserted automatically in a dictionary and write into a file

Time:02-19

I want to create ID for each element inserted in an empty dictionary then write it in a file as in the picture below. But it doesn't work. Any help to fix it?

dict ={}
ids = 0
line_count = 0 
fhand = input('Enter the file name:')
fname = open(fhand,'a ')
for line in fname:
   if line.split() == []:
       ids = 1
   else:
       line_count  =1
       ids = line_count  1
n = int(input('How many colors do you want to add?'))
for i in range (0,n):
   dict['ID:'] = ids   1
   dict['Color:'] = input('Enter the color:')
   for key,value in dict.items():
           s = str(key) ' ' str(value) '\n'
           fname.write(s)
fname.close()
print('Done!') ```


Output should be: 

ID : 1
Color: red
ID : 2
Color : rose 
ID : 3
Color : blue

CodePudding user response:

Not sure if I got what you meant but...

A dictionary is made of <key, value> pairs.

Let`s suppose you have a dictionary:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

If you want to create a ID for each key (for a specific reason) you could use a for loop like:

for key in thisdict.keys():
    createIdFunction(key)

And have a createIdFunction which is going to assign a ID based on whatever you want.

Suggestion: Dictionaries can only hold unique keys, so maybe you could use their own keys as ID.

However if your dictionary is empty, there would be no reason to have a ID for that key, right?

CodePudding user response:

You mean your id is not increased ? I think you did not reassign variable "ids" in loop, you may modify code as below:

dict ={}
ids = 0
line_count = 0 
fhand = input('Enter the file name:')
fname = open(fhand,'a ')
for line in fname:
   if line.split() == []:
       ids = 1
   else:
       line_count  =1
       ids = line_count  1
n = int(input('How many colors do you want to add?'))
for i in range (0,n):
   ids  = 1 # modified
   dict['ID:'] = ids # modified
   dict['Color:'] = input('Enter the color:')
   for key,value in dict.items():
       s = str(key) ' ' str(value) '\n'
       fname.write(s)
fname.close()
  • Related