通过输入Python将元素添加到字典中

时间:2018-04-25 12:35:19

标签: python dictionary

我需要使用用户输入创建这样的字典:

a = {
'1': {'2': 2, '3': 5, '4': 1},
'2': {'1': 2, '3': 2, '4':4},
'3': {'1': 5, '2':2},
'4': {'1': 1, '2': 4, '5':3}, 
'5': {'4':3}}

例如,在输入中我必须写" 2 2 3 5 4 1"这些值转到指数N.1" {' 1':{' 2':2,' 3':5,' 4':1}"

我一直试图这样做但我无法成功。 我试图在许多论点中使用for和split列表,但我仍然没有结论。

感谢您的回答。

3 个答案:

答案 0 :(得分:1)

一种方法是使用str.split并使用itertools.islice

from itertools import islice

input_str = '2 2 3 5 4 1'

def zipper(mystr):
    split = mystr.split()
    return zip(islice(split, 0, None, 2), islice(split, 1, None, 2))

d = {}
d['1'] = dict({k: int(v) for k, v in zipper(input_str)})

# {'1': {'2': 2, '3': 5, '4': 1}}

答案 1 :(得分:0)

您可以使用以下代码向dict添加元素:

dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
dict[index] = [7, 8, 9]

答案 2 :(得分:0)

使用input获取数据,split在空格处分解数据:

response = input('Enter digits separated by spaces').split()

现在是一个循环,一直持续到用户不再提供任何输入:

while response:
    payload = response[:-1]   # all but the last number
    index = response[-1]      # this is your dictionary key
    # Now count the repetitions in the user's input and assign to a[index]
    a[index] = {k: payload.count(k) for k in payload}  
    # And ask for more input
    response = input('Enter more digits (press Enter to finish)').split()

然后显示结果:

print(a)