简体   繁体   中英

Python - Dictionary with Lists and tuples

End Goal to create the following Dictionary

DictFinal = {'peach': [7,33], 'berries': [33,47], 'grapes': [47,98], 'apple': [98,200]}

snippets of code

FinalEndofline = 200
List1 = ["apple","peach","grapes","berries"]
List2 = [98,7,47,33]

Step1 : To create a dictionary using key value.List1 is the key and List2 is value.

professions_dict = dict(zip(List1, List2))
print professions_dict

Output - {'apple': 98, 'peach': 7, 'grapes': 47, 'berries': 33}

Step 2 : Sort the dictionary based on value

sorted_x = sorted(professions_dict.items(), key=operator.itemgetter(1))
print sorted_x

Output - {'peach': 7, 'berries': 33, 'grapes': 47, 'apple': 98}

Step 3 : Now how do I achieve

DictFinal = {'peach': [7,33], 'berries': [33,47], 'grapes': [47,98], 'apple': [98,200]}

The Dictfinal is again a key value, but a value having the list with first value and second value and goes on and it appends the finalendofline variable to last value list

Maybe try:

List2 = ["""Blah""",FinalEndofLine]
unsorted = dict(zip(List1,[[List2[i],List2[i+1]] for i in range(len(l2) - 1)]))
DictFinal = sorted(unsorted.items(), key = lambda x: x[1][0])

This seemed to work for me, if I understand your problem fully. List2 just needs that FinalEndofLine at the end.

>>> List1 = ["apple","peach","grapes","berries"]
>>> List2 = [98,7,47,33]
>>> List1 = [x[1] for x in sorted(zip(List2, List1))]
>>> List2.sort()
>>> List2.append(200)
>>> DictFinal = dict((key, List2[i:i+2]) for i, key in enumerate(List1))
>>> DictFinal
{'berries': [33, 47], 'grapes': [47, 98], 'peach': [7, 33], 'apple': [98, 200]}

That's fairly straightforward. This is probably a bit more efficient, though -- only requires one sort() . If efficiency really matters, you could also use itertools to do the slice on the second zip (and, of course, with Python 2, you would want to use izip instead of zip).

>>> List1 = ["apple","peach","grapes","berries"]
>>> List2 = [98,7,47,33]
>>> zipped = sorted(zip(List2, List1)) + [(200,)]
>>> FinalDict = dict((x[1], [x[0], y[0]]) for x, y in zip(zipped, zipped[1:]))

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