Ritesh
Ritesh

Reputation: 75

Printing output to file

i have a dict as below. I want the output to be directed to a file say 'insert.sql'. I am trying to print the result set here. and I need help with sending this output to a file. So far this is the code i have written. What am I missing here.

Expected Output:

insert into abc values (
'india',
'china'
);

Observed output:

insert into abc values (
'china'
);

Code:

newdict = {'asia': 'india',
           'asia': 'china'}

print("insert into abc values (")
for i, (k, v) in enumerate(newdict.items()):
    if i:
        print(",")
    print("'" + v + "'", end="")
print("\n);")

Upvotes: 0

Views: 87

Answers (3)

cel16
cel16

Reputation: 119

You are using the same key in the dictionary so 'india' is replaced by 'china'. Try to make it into a list.

newdict = {'asia': ['india', 'china']}

print("insert into abc values (")
for i, (k, v) in enumerate(newdict.items()):    
    for j, country in enumerate(v):
        print("'" + country + "'", end="")
        if j!=(len(v)-1):
            print(",")
print("\n);")

Upvotes: 1

Zubda
Zubda

Reputation: 963

Your issue is that you are creating a dictionary and duplicating a key in it which effectively creates a dictionary with the last value as the value for the key,

>>> {'a': 10, 'a': 20}
{'a': 20}

(which is just like doing:

>>> data = {'a': 10}
>>> data['a'] = 20
>>> data
{'a': 20}

In your case I think you would need to use a list of values for each key, i.e.

>>> data = {'asia': ['india', 'china']}
>>> for continent, countries in data.items():
...     for country in countries:
...         print(continent, country)
... 
asia india
asia china

BTW, there is no need to use enumerate and check whether ther is an index as the for loop will terminate if there is no element

Upvotes: 1

Radosław Cybulski
Radosław Cybulski

Reputation: 2992

Try:

with open('insert.sql', 'w') as output:
    print("insert into abc values (", file=output)
    for i, (k, v) in enumerate(newdict.items()):
        if i:
            print(", ", file=output)
        print("'" + v + "'", end="", file=output)
    print("\n);", file=output)

print's file argument allows you to pass file, to which print's output will be written instead of default standard output.

EDIT: since you're using only values you can use somewhat shorter version:

for i, v in enumerate(newdict.values()):

Upvotes: 1

Related Questions