Seems simple, yet elusive, want to build a dict from input of [key,value] pairs separated by a space using just one Python statement. This is what I have so far:
d={}
n = 3
d = [ map(str,raw_input().split()) for x in range(n)]
print d
Input:
A1023 CRT
A1029 Regulator
A1030 Therm
Desired Output:
{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}
To add user input to a dictionary in Python:Declare a variable that stores an empty dictionary. Use a range to iterate N times. On each iteration, prompt the user for input. Add the key-value pair to the dictionary.
Practical Data Science using PythonYou can assign a dictionary value to a variable in Python using the access operator [].
Creating Python Dictionary Creating a dictionary is as simple as placing items inside curly braces {} separated by commas. An item has a key and a corresponding value that is expressed as a pair (key: value).
You can easily convert python string to the dictionary by using the inbuilt function of loads of json library of python. Before using this method, you have to import the json library in python using the “import” keyword.
This is what we ended up using:
n = 3
d = dict(raw_input().split() for _ in range(n))
print d
Input:
A1023 CRT
A1029 Regulator
A1030 Therm
Output:
{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}
n = int(input("enter a n value:"))
d = {}
for i in range(n):
keys = input() # here i have taken keys as strings
values = int(input()) # here i have taken values as integers
d[keys] = values
print(d)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With