Selecting a random tuple from a dictionary - python

Say I have this:
d={'a':[(1,2),(3,4)],'b':[(9,2),(5,4)],'c':[(2,2),(7,7)]}
where d is a dictionary in python. I'd like to get random tuples out of this corresponding to a particular key using the random.choice() method.
This is what I'm doing and it's not working:
random.choice(d['a'].values())

d['a'] is already a list, so you don't need to call .values() on it.
import random
d = {
'a': [(1, 2), (3, 4)],
'b': [(9, 2), (5, 4)],
'c': [(2, 2), (7, 7)],
}
print(random.choice(d['a']))

If you're just trying to get a random tuple out of key you pick, you've written too much:
random.choice(d['a'])
(Also NB: You'll need quotes around the keys in the dictionary. Right now you're using, e.g., the undefined variable a instead of the string 'a'.)

Related

merging two lists of tuples in python

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'])]

python collection of tuples to dictionary

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}

Python 2.7.3: Take an item from a list and make it a key in a dictionary

I want to take items from a list and put them into a dictionary.
Say we have the following
carList = set(zip(carWordList, carWordFreq))
note: I use set to remove duplicates
So carList would produce the following:
set([('merry', 3), ('cop', 25), ('completely', 21), ('jaw', 2), ('fiddle', 1), ('bright', 4), ('593', 1), ('asked', 22), ('additionally', 4), ('pretend', 1), ('beam', 4)])
Now I want to take the words (ex. 'merry') and make them keys in a dictionary (newDic) with the numbers as values.
Also, I want to use that new dictionary to create another dictionary (otherDic) that has two keys (one being the word (ex. 'merry') and another being "Car", which will take a value later
for key in newDic:
otherDic = [key]["Car"]
I tried to do the following:
for key in carList:
otherDic = [key]["Car"]
However, I get the following error:
TypeError: list indices must be integers, not str
When you do this
otherDic = [key]["Car"]
You are just creating a list [key] that contains only key, and then you are trying to index it with "Car" instead of with an integer, which is why you get the error.
Secondly, you can't start looping into this for key in newDic: without ever creating the newDic which I don't see you doing at any point.
Anyway, this is the wrong way to approach your problem. To turn your set into a dictionary you can simply do this:
my_dict = {key: value for key, value in carList}
That's called dictionary comprehension by the way. But as #Adam Smith pointed out, that is actually equivalent to
my_dict = dict(carList)
Which is simpler... But after that, I don't quite understand what you mean by creating another dict with 2 keys per value. You can't create a dict with 2 keys, that's not how they work. You could comment here on the desired output of this new dict and I will edit my answer.
You can use dictionary comprehension:
In [61]: l = set([('merry', 3), ('cop', 25), ('completely', 21), ('jaw', 2), ('fiddle', 1), ('bright', 4), ('593', 1), ('asked', 22), ('additionally', 4), ('pretend', 1), ('beam', 4)])
In [63]: d = {k:v for k,v in l}
In [64]: d
Out[64]:
{'593': 1,
'additionally': 4,
'asked': 22,
'beam': 4,
'bright': 4,
'completely': 21,
'cop': 25,
'fiddle': 1,
'jaw': 2,
'merry': 3,
'pretend': 1}

Using operator.itemgetter to handle dictionary sorting

Referring to the below code, the first for loop can be easily used for the sorting in the dictionary and it works very well.
import operator
myExample = {'Item1': 3867, 'Item2': 20, 'Item3': 400, 'Item4': 100, 'Item5': 2870,
'Item6': 22, 'Item7': 528, 'Item8': 114}
for w in sorted(myExample, key=myExample.get, reverse=False):
print w, myExample[w]
print ("\n")
for w in sorted(myExample, key=operator.itemgetter(0)):
print w, myExample[w]
But somehow I was told by the other thread, it is advice to use operator.itemgetter(index) method to perform the sorting due to the efficiency reason. But the second for loop is never works in my case.
Perhaps I should go through the documentation first and this is what I get:
>>> itemgetter(1)('ABCDEFG')
'B'
>>> itemgetter(1,3,5)('ABCDEFG')
('B', 'D', 'F')
>>> itemgetter(slice(2,None))('ABCDEFG')
'CDEFG'
The example is simple, But to be honest, I don't know how to link this back to the dictionary case. How should I use the index inside the itemgetter and different index will have what kind of impact? I tried all index from 0 to 4 and none of them give me an ascending sorting result and error will occur starting from index 5.
In a document, there is a example for tuple case, but it's not works for the dictionary.
>>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
>>> getcount = itemgetter(1)
>>> map(getcount, inventory)
[3, 2, 5, 1]
>>> sorted(inventory, key=getcount)
[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
Back to the Origin, I still hope to understand how to use the index inside the itemgetter and what it does in different cases like tuple vs. dictionary vs. list vs. only a string vs. tuple inside a list, and etc.
Please advise.

How to get an ordered output from a Dictionary in python?

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

Categories

Resources