开发者

Python Dictionary Ordered Pairs

开发者_StackOverflow

Ok, I need to create a program that accepts ordered pairs divided by a space, and adds them to the dictionary.

I.e

points2dict(["3 5"])  
{"3":"5"}

How do i make python recognize that the first number is the key and the second number is the value???


Use split:

In [3]: pairs = ['3 5', '10 2', '11 3']

In [4]: dict(p.split(' ', 1) for p in pairs)
Out[4]: {'10': '2', '11': '3', '3': '5'}


values = [
    '3 5',
    '6 10',
    '20 30',
    '1 2'
]
print dict(x.split() for x in values)
# Prints: {'1': '2', '3': '5', '20': '30', '6': '10'}


For your simple example in which there are only pairs of numbers, always separated by a space with no validation needed:

def points_to_dict(points):
    #create a generator that will split each string of points
    string_pairs = (item.split() for item in points)
    #convert these to integers
    integer_pairs = ((int(key), int(value)) for key, value in string_pairs)
    #consume the generator expressions by creating a dictionary out of them
    result = dict(integer_pairs)
    return result

values = ("3 5", ) #tuple with values
print points_to_dict(values) #prints {3: 5}

Of important note is that this will give you integer keys and values (I'm assuming that's what you want and it's a more interesting transform to illustrate anyway). This will also perform better than python loops and even the map builtin (the deferred execution allows the generators to stack instead of allocating memory for the intermediate results).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜