Access individual elements of tuples of dictionary keys - python

Considering the code snippet below -
list1 = [1,2,3,4]
list2 = [1,2,3,4]
list3 = ['a','b','c','d']
dct = dict(zip(zip(list1,list2),list3))
print(dct)
gives me,
{(1, 1): 'a', (2, 2): 'b', (3, 3): 'c', (4, 4): 'd'}
Now,
print(dct.keys())
gives me,
dict_keys([(1, 1), (2, 2), (3, 3), (4, 4)])
How can i access first element of the above list of keys?
Something like -
dct.keys[0, 0] = 1
dct.keys[0, 1] = 1
dct.keys[1, 0] = 2
dct.keys[1, 2] = 2
and so on...

Remember that a dict is unordered, and that dict.keys() may change order.
That said, to access the first element of a list, as you said, you can use list[element_index]. If the elemnt is an iterable, do that again!
So it would be
dct_keys = list(yourdict.keys())
dct_keys[0][0] = 1
dct_keys[0][1] = 1
dct_keys[1][0] = 2
dct_keys[1][1] = 2

You need to first convert the dct.keys() output to a list, and then the problem reduces to simple list-of-tuples indexing. To convert your .keys() output to a list, there are multiple available ways (check this out). Personally, I find using list comprehension as one of the simplest and most generic ways:
>>> [key for key in dct.keys()]
[(1, 1), (2, 2), (3, 3), (4, 4)]
And now simply index this list of tuples as:
>>> [key for key in dct.keys()][0][0]
1
Hope that helps.

Related

How can I make a new list where each list is based on an items index in the main list?

For example:
Mainlist = [[1,2,3,4],[1,2,3,4]]
output = [1,1],[2,2],[3,3],[4,4]
Mainlist should be split based on indexes of each value in the sublists. So each value at index[0] should be grouped with the other values an index[0], and so on.
Is there a simple pythonic way to do this?
Use zip() to pair up elements of two lists.
>>> Mainlist = [[1,2,3,4],[1,2,3,4]]
>>> output = list(zip(*Mainlist))
>>> output
[(1, 1), (2, 2), (3, 3), (4, 4)]

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

Get the second value in a tuple by using the first value in a tuple

As in the title, is there a way to access the second value of a tuple by using the first one?
For example: given a list of tuple: [('Street', 2), ('Utilities', 3), ('CentralAir', 5)], can we access the value '5' by using the index 'CentralAir'?
For your use case it's more convenient to build a dict to get the value you need.
Example:
>>> tuples = [('Street', 2), ('Utilities', 3), ('CentralAir', 5)]
>>> d = dict(tuples)
>>> d
{'Street': 2, 'Utilities': 3, 'CentralAir': 5}
>>> d['CentralAir']
5
a very simple solution
ar = [('Street', 2), ('Utilities', 3), ('CentralAir', 5)]
value = next(filter(lambda x: x[0] == 'CentralAir', ar))[1] # returns 5

How to nest tuples in Python

I am very new at Python. I am trying to do a tuple that contains tuples in the form (1,(1,(1,'a'))). I am not allowed to use any functions. I have written a list and for each element of the list I want to take tuple.
I want to take something like (2,(3,(4,'name'))) and the result I take is (2,3,4,'name').
b = [6,5,4,3,2,1]
for i in range(len(b)):
mytuple = (i,'name')
print(i)
mytuple = (b[2],)+mytuple
print(mytuple)
Iterate reverse on b:
t="name"
for i in range(-1,-len(b)-1,-1):
t=(b[i],t)
Out: (6, (5, (4, (3, (2, (1, 'name'))))))

Python: mapping a list of lists onto a dictionary

If I have a list like this
l=[[(1, 2), (1, 3)], [(1, 2), (2, 3)], [(1, 3), (2, 3)]]
and a dictionary like this
d={(1, 2): 3.61, (1, 3): 5.0, (2, 3): 6.0}
and I want to produce a list of lists that contains the values in d associated with the keys that appear in l, like this
newlist=[[3.61,5.0],[3.61,6.0],[5.0,6.0]]
How could I do it?
My attempt is
newlist=[v for k, v in d.items() if l[[i]]==k for i in l]
but this returns
TypeError: list indices must be integers, not list
Your attempt does not work because first of all the result should be a list of lists: your list comprehension will (if it would work) construct a list of values.
Furthermore it would loop only once over the dictionary (since that is the left for loop).
You can do this less error-prone and more efficient with:
newlist = [[d[x] for x in li] for li in l]
This will work given all tuples are keys in the dictionary d. If that is not the case, you can use .get(..) and specify a default value (for instance None):
newlist = [[d.get(x,None) for x in li] for li in l]

Categories

Resources