K R
K R

Reputation: 74

Reading input as dictionary in python

Im trying to read input spread across multiline in form of dictionary and apply simple math operations on the value of dictionary . My code reads

d ={} 
bal=0
text = input().split(",")   #split the input text based on line'text'
print(text)

for i in range(5):        
    text1 = text[i].split(" ")  #split the input text based on space &   store in the list 'text1'
    d[text1[0]] = int(text1[1]) #assign the 1st item to key and 2nd item to value of the dictionary
print(d)

for key in d:
    if key=='D':
        bal=bal+int(d[key])
        #print(d[key])
    elif key=='W':
        bal=bal-int(d[key])

print(bal)

Input : W 300,W 200,D 100,D 400,D 600 output :{'D': 600, 'W': 200} 400 Expected Output: {'W':300,'W':200,'D':100,'D':400,'D':600} 600

ISSUE: The issue here is the code always reads 2 and last values only . For example in the above case output is {'D': 600, 'W': 200} 400

Can someone let me know the issue with for loop . Thanks in advance

Upvotes: 1

Views: 223

Answers (1)

hygull
hygull

Reputation: 8740

You can try like this in a simpler way using your own approach. @Rakesh and @Sabesh suggested good. Dictionary is an unordered collection with unique and immutable keys. You can easily check this on your Python interactive console by executing help(dict).

You can check https://docs.python.org/2/library/collections.html#collections.defaultdict . Here you'll find number of examples on how to efficiently using dictionary.

>>> d = {}
>>> text = 'W 300,W 200,D 100,D 400,D 600'
>>>
>>> for item in text.split(","):
...     arr = item.split()
...     d.setdefault(arr[0], []).append(arr[1])
...
>>> d
{'W': ['300', '200'], 'D': ['100', '400', '600']}
>>>
>>> w = [int(n) for n in d['W']]
>>> d = [int(n) for n in d['D']]
>>>
>>> bal = sum(d) - sum(w)
>>> bal
600
>>>

Upvotes: 1

Related Questions