Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a dictionary in Python from input values

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'}
like image 387
Beta Projects Avatar asked Jan 03 '13 21:01

Beta Projects


People also ask

Can you build a dictionary off of user input in Python?

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.

Can you assign a value to be a dictionary in Python?

Practical Data Science using PythonYou can assign a dictionary value to a variable in Python using the access operator [].

How do you create a data dictionary in Python?

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).

Can you turn a string into a dictionary Python?

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.


2 Answers

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'}
like image 50
Beta Projects Avatar answered Oct 20 '22 14:10

Beta Projects


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)
like image 26
Surendra Kumar Aratikatla Avatar answered Oct 20 '22 16:10

Surendra Kumar Aratikatla