简体   繁体   中英

How to create a dictionary from input string in Python3

I have a 4 lines in input that looks like:

first 10
second 20
third 30
fourth 40

And i want to create a dict with words as key and number as value:

{ 
    'first': 10,
    'second': 20,
    'third': 30'
    'fourth': 40
}

How to do this by using dict comprehension? So this is working:

d = {}
for i in range(4):
    s = input().split()
    d[s[0]] = s[1]

And this is not:

x = {s: v for k in range(4) for s, v in input().split()}

尽管Jean已经提供了答案,但我想我也应该添加一个答案,它使用生成器来获取并拆分输入,然后将dict理解成字典。

{ k : v for k, v in (input().split() for _ in range(4)) }

You're iterating on the value of the split result in the inner loop, where you just need to assign & unpack the split values. Unfortunately you cannot do that inside a list comprehension.

But you could pass a generator comprehension yielding couples instead of a dictionary comprehension

x = dict(input().split() for k in range(4))

that's simple but doesn't convert strings to integers, though. To convert the second item to integers while remaining in the list comprehension, you could use enumerate on the split result and test if this is the 2nd item using a ternary expression, which complexifies the line but yields the value as integer.

x = dict([int(x) if i==1 else x for i,x in enumerate(input().split())] for k in range(4))

You're simply splitting on whitespace and that won't give you the desired pairs. It would give you a list of the words separated by whitespace (like ['first', '10', second', '20'] ). Try something like:

x = {item.split()[0]: item.split()[1] for item in input().split('\\n')}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM