I have created a program using python Dictionary. In this simple program i can not understand the memory structure of the dictionary. And when I retrieve the data from the dictionary at that time the data is not retrieve in the sequence.
Digit = {1 : One, 2: Two,3: Three,4: Four,5: Five,6: Six,7: Seven,8: Eight,9: nine,0: Zero}
print Digit
It will give me the output like thatTwo,Three,Five,Four etc. If I want it ordered in sequence what do I have to do ?
Dictionaries are arbitrarily ordered in Python. The order is not guaranteed and you should not rely on it. If you need an ordered collection, use either OrderedDict or a list.
If you want to access the dictionary in key order, first get a list of the keys then sort it and then step through that:
keys = Digit.keys()
keys.sort()
for i in keys:
print Digit[i]
If you absolutely want to store ordered data, you could use OrderedDict as Burhan Khalid suggested in his answer:
>>> from collections import OrderedDict
>>> Digit = [(1, "One"), (2, "Two"), (3, "Three"), (4, "Four"), (5, "Five"), (6, "Six"), (7, "Seven"), (8, "Eight"), (9, "Nine"), (0, "Zero")]
>>> Digit = OrderedDict(Digit)
>>> Digit
OrderedDict([(1, 'One'), (2, 'Two'), (3, 'Three'), (4, 'Four'), (5, 'Five'), (6, 'Six'), (7, 'Seven'), (8, 'Eight'), (9, 'Nine'), (0, 'Zero')])
>>> for k,v in Digit.items():
... print k, v
...
1 One
2 Two
3 Three
4 Four
5 Five
6 Six
7 Seven
8 Eight
9 Nine
0 Zero
Related
let's assume these are my lists:
oracle_files = [
(1, "__init__.py"),
(2, "price_calc.py"),
(3, "lang.py")]
predicted_files = [
(5, ["random.py","price_calc.py"]),
(2, ["__init__.py","price_calc.py"]),
(1, ["lang.py","__init__.py"])]
first list is a list of tuples where i have an identifier and a string per each.
second one is a list of tuples of integers and list of strings
my intention is to create a third list that intersects these two ones by ID (the integer)
and the output should look like this:
result = [(2, "price_calc.py", ["__init__.py","price_calc.py"]),
(1, "__init__.py", ["lang.py","__init__.py"])]
do you know a way to reach this output? because i'm not getting it right.
Here's an approach using dict:
oracle_files = [(1, "__init__.py"), (2, "price_calc.py"), (3, "lang.py")]
predicted_files = [(5, ["random.py","price_calc.py"]), (2, ["__init__.py","price_calc.py"]), (1, ["lang.py","__init__.py"])]
dct1 = dict(oracle_files)
dct2 = dict(predicted_files)
result = [(k, dct1[k], dct2[k]) for k in dct1.keys() & dct2.keys()]
print(result) # [(1, '__init__.py', ['lang.py', '__init__.py']), (2, 'price_calc.py', ['__init__.py', 'price_calc.py'])]
This uses a convenient fact that the dict keys obtained from dict.keys() behave like a set.
Keys views are set-like since their entries are unique and hashable. [...] For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^).
https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects
I think this does what you want.
oracle_files = [(1, "__init__.py"), (2, "price_calc.py"), (3, "lang.py")]
predicted_files = [(5, ["random.py","price_calc.py"]), (2, ["__init__.py","price_calc.py"]), (1, ["lang.py","__init__.py"])]
dct = dict(oracle_files)
for k,v in predicted_files:
if k in dct:
dct[k] = (dct[k], v)
print(dct)
outlist = [(k,)+v for k,v in dct.items() if isinstance(v,tuple)]
print(outlist)
Output:
{1: ('__init__.py', ['lang.py', '__init__.py']), 2: ('price_calc.py', ['__init__.py', 'price_calc.py']), 3: 'lang.py'}
[(1, '__init__.py', ['lang.py', '__init__.py']), (2, 'price_calc.py', ['__init__.py', 'price_calc.py'])]
I have the following data structure in Python 3:
foo = [(1, 'ADTABC', 7), (3, 'ACHDAT', 8), (1, 'AQNDXB', 15), (2, 'AFTCBA', 14)]
The first and second elements of each tuple are guaranteed to be unique together. I want to create a dictionary that has as the key the concatenation of the first and second elements and as the value the third element:
{'1ADTABC': 7, '3ACHDAT': 8, '1AQNDXB': 15, '2AFTCBA': 14}
How do I achieve this?
Why? The collection you see is the result of a SqlAlchemy query. The third field is the unique id in the database. I need to quickly and efficiently retrieve the Id given the other two elements. Since these values do not really get updated, there is no need to make roundtrips to the db for the retrieval.
You can do that without string concat like:
Code:
foo_dict = {x[0:2]: x[2] for x in foo}
String concat is not the best way to go about this since it requires the creation of yet a another object, but does actual create any extra information. A tuple will use the original objects, but still achieve the need to key a dict.
Test Code:
foo = [(1, 'ADTABC', 7), (3, 'ACHDAT', 8), (1, 'AQNDXB', 15), (2, 'AFTCBA', 14)]
foo_dict = {x[0:2]: x[2] for x in foo}
print(foo)
print(foo_dict)
Results:
[(1, 'ADTABC', 7), (3, 'ACHDAT', 8), (1, 'AQNDXB', 15), (2, 'AFTCBA', 14)]
{(1, 'ADTABC'): 7, (3, 'ACHDAT'): 8, (1, 'AQNDXB'): 15, (2, 'AFTCBA'): 14}
h = {str(a) + b: c for a,b,c in foo}
I have a list of tuples, each tuple contains two integers. I need to sort the the list (in reverse order) according to the difference of the integers in each tuple, but break ties with the larger first integer.
Example
For [(5, 6), (4, 1), (6, 7)], we should get [(4, 1), (6, 7), (5, 6)].
My way
I have already solved it by making a dictionary that contains the difference as the key and the tuple as the value. But the whole thing is a bit clumsy.
What is a better way?
Use a key function to sorted() and return a tuple; values will be sorted lexicographically:
sorted(yourlst, key=lambda t: (abs(t[0] - t[1])), t[0]), reverse=True)
I'm using abs() here to calculate a difference, regardless of which of the two integers is larger.
For your sample input, the key produces (1, 5), (3, 4) and (1, 6); in reverse order that puts (1, 6) (for the (6, 7) tuple) before (1, 5) (corresponding with (5, 6)).
Demo:
>>> yourlst = [(5, 6), (4, 1), (6, 7)]
>>> sorted(yourlst, key=lambda t: (abs(t[0] - t[1]), t[0]), reverse=True)
[(4, 1), (6, 7), (5, 6)]
Given this list=[('a','b',3),('d','e',3),('e','f',5)], if you'd like to sort by the number in descending order, but break ties (when counts are equal like with the '3' on this example) using ascending alphabetical order of the first element and then the second element repectively, the following code works:
sorted(list,key=lambda x: (-x[2],x[0],x[1]))
Here the '-' sign on the x[2] indicates it needs to be sorted in the descending order.
The output will be: [('e', 'f', 5), ('a', 'b', 3), ('d', 'e', 3)]
This question already has answers here:
How to test if a list contains another list as a contiguous subsequence?
(19 answers)
Closed 9 years ago.
I have 2 lists one :
[(12,23),(12,45),(12,23),(2,5),(1,2),(2,4),(7,34)] which goes up to around 1000 elements
and another:
[(12,23),(12,45),(12,23),(2,5),(1,2),(2,66),(34,7)] which goes up to around 241 elements.
What I want is to check to see if the lists contain any of the same elements and then put them in a new list.
so the new list becomes
[(12,23),(12,45),(12,23),(2,5),(1,2)]
This doesn't include duplicates
>>> A = [(12,23),(12,45),(12,23),(2,5),(1,2),(2,4),(7,34)]
>>> B = [(12,23),(12,45),(12,23),(2,5),(1,2),(2,66),(34,7)]
>>> set(B).intersection(A) # note: making the smaller list to a set is faster
set([(12, 45), (1, 2), (12, 23), (2, 5)])
Or
>>> A = [(12,23),(12,45),(12,23),(2,5),(1,2),(2,4),(7,34)]
>>> B = [(12,23),(12,45),(12,23),(2,5),(1,2),(2,66),(34,7)]
>>> filter(set(B).__contains__, A)
[(12, 23), (12, 45), (12, 23), (2, 5), (1, 2)]
This returns every item in B if it occured in A, which produces the result you give in the example, however the set is probably what you want.
Since I don't know exactly what you are using this for, I'll suggest one more solution which returns a list, containing the items that occur in both lists, the minimum amount of times they occurred in either list (unordered). This differs from the set solution above which only returns each item the number of times it occurred in the other and doesn't care how many times it occurred in the first. This uses Counter for the intersection of multisets.
>>> from collections import Counter
>>> A = [(12,23),(12,45),(12,23),(2,5),(1,2),(2,4),(7,34)]
>>> B = [(12,23),(12,45),(12,23),(2,5),(1,2),(2,66),(34,7)]
>>> list((Counter(A) & Counter(B)).elements())
[(1, 2), (12, 45), (12, 23), (12, 23), (2, 5)]
Let's say I have the following two lists of tuples
myList = [(1, 7), (3, 3), (5, 9)]
otherList = [(2, 4), (3, 5), (5, 2), (7, 8)]
returns => [(1, 7), (2, 4), (3, 8), (5, 11), (7, 8)]
I would like to design a merge operation that merges these two lists by checking for any intersections on the first element of the tuple, if there are intersections, add the second elements of each tuple in question (merge the two). After the operation I would like to sort based upon the first element.
I am also posting this because I think its a pretty common problem that has an obvious solution, but I feel that there could be very pythonic solutions to this question ;)
Use a dictionary for the result:
result = {}
for k, v in my_list + other_list:
result[k] = result.get(k, 0) + v
If you want a list of tuples, you can get it via result.items(). The resulting list will be in arbitrary order, but of course you can sort it if desired.
(Note that I renamed your lists to conform with Python's style conventions.)
Use defaultdict:
from collections import defaultdict
results_dict = defaultdict(int)
results_dict.update(my_list)
for a, b in other_list:
results_dict[a] += b
results = sorted(results_dict.items())
Note: When sorting sequences, sorted sorts by the first item in the sequence. If the first elements are the same, then it compares the second element. You can give sorted a function to sort by, using the key keyword argument:
results = sorted(results_dict.items(), key=lambda x: x[1]) #sort by the 2nd item
or
results = sorted(results_dict.items(), key=lambda x: abs(x[0])) #sort by absolute value
A method using itertools:
>>> myList = [(1, 7), (3, 3), (5, 9)]
>>> otherList = [(2, 4), (3, 5), (5, 2), (7, 8)]
>>> import itertools
>>> merged = []
>>> for k, g in itertools.groupby(sorted(myList + otherList), lambda e: e[0]):
... merged.append((k, sum(e[1] for e in g)))
...
>>> merged
[(1, 7), (2, 4), (3, 8), (5, 11), (7, 8)]
This first concatenates the two lists together and sorts it. itertools.groupby returns the elements of the merged list, grouped by the first element of the tuple, so it just sums them up and places it into the merged list.
>>> [(k, sum(v for x,v in myList + otherList if k == x)) for k in dict(myList + otherList).keys()]
[(1, 7), (2, 4), (3, 8), (5, 11), (7, 8)]
>>>
tested for both Python2.7 and 3.2
dict(myList + otherList).keys() returns an iterable containing a set of the keys for the joined lists
sum(...) takes 'k' to loop again through the joined list and add up tuple items 'v' where k == x
... but the extra looping adds processing overhead. Using an explicit dictionary as proposed by Sven Marnach avoids it.