How to access specific element of dictionary of tuples - python

I want to access a specific element of a tuple in a dictionary of tuples. Let's say that I have a dictionary with a unique key, and a tuple with three values, for each key. I want to write a iterator the prints every third item in a tuple for every element in the dictionary.
For example
dict = {"abc":(1,2,3), "bcd":(2,3,4), "cde", (3,4,5)}
for item in dict:
print item[2]
But this returns
c
d
e
Where am I going wrong?

for item in dict:
print dict[item][2]
Also, you should not name anything after a built-in, so name your dictionary 'd' or something other than 'dict'
for item in dict: does the same thing as for item in dict.keys().
Alternatively, you can do:
for item in dict.values():
print item[2]

Your code is close, but you must key into the dictionary and THEN print the value in index 2.
You are printing parts of the Keys. You want to print parts of the Values associated with those Keys:
for item in dict:
print dict[item][2]

Related

How to compare a value with a list of dicts without using for loop in python?

Input:
value = "apple"
dict = [{'name':'apple','color':"red"},{'name':'orange','color':"orange"}]
Witout using the for loop like below, is it possible to compare and get the values?
Code I have done:
for i in dict:
if i["name"] == value:
print i
You do have multiple dicts in a list, not just one.
Therefore you must go through all items in your list.
for d in dict: # dict is actually a list, but I am using your var name
if value in d.values():
print(value)

How to access a dictionary value with a list index number in python?

Hey guys hereĀ“s my problem.
Lets say I have two dictionaries and a list containing both dictionaries:
a={1:"hello",2:"goodbye"}
b={1:"Hi",2:"Farewell"}
list1=[a,b]
Now, if I iterate over the entire list like this, everything works fine:
for e in list1:
print(e[1])
However, whenever I try to iterate over the list by using the list index number, python throws an error message ("TypeError: 'int' object has no attribute 'getitem'")
for e in list1[0]:
print(e[1])
Could someone explain how I can access the dictionary value of a certain item in a list with a list index number?
Thanks in advance for your help!
the problem is that list1[0] is a dictionary, and when using the way you are doing in a for loop, it'l iterate over the keys of that dictionary
so in your case, for the first iteration the e variable is of type int with the value 1, in the second iteration it has the value 2.
so if you want to iterate over the keys, and values of a dictionary you should use
for key, val in list1[0].items():
print('key: {}, value {}'.format(key, val))
You can try:
a = {1: "hello", 2: "goodbye"}
b = {1: "Hi", 2: "Farewell"}
list1 = [a, b]
for index, dict_data in enumerate(list1):
print(index)
print(dict_data)
you can use the .get method like this:
for d in list1:
for i in d:
print(d.get(i))
maybe this can help you
list1[0] is a dict. using for ... in ... on a dict iterates the keys, and your keys are ints.
try:
for e in list1[0]:
print(e)
print(list1[0][e])
Just do:
for e in list1[0]:
print(e)
Dictionary entries aren't stored in a given order, so the output won't be what you expect. However, you can do next(e.values()).

How to access multiple dictionaries values of the same keys from a list?

I have this list:
f = ['a','b','c',['me','you','him/her'],
{'apples':430,'peaches':239,'bananas':839},
{'apples':123,'peaches':345,'bananas':536}]
I know i can access each item in this list if i use slices. For example to access the first dictionary i would do a
print(f[4]) #---> {'apples': 430, 'peaches': 239, 'bananas': 839}
To access a value of a key in the dictionary i do it like this:
print(f[4]['apples']) #---> 430
My question is how can i access the values of both apples keys (430,123) in those 2 separate dictionaries, to be displayed one after another automatically?
Can someone please advise, on how to fix this?
Thanks.
You can use a list comprehension to do this.
Note that without the if statement, you will get a KeyError if the dict doesn't have the "apples" key and TypeError if the item in the list is not a dict
>>> f = ['a','b','c',['me','you','him/her'],
... {'apples':430,'peaches':239,'bananas':839},
... {'apples':123,'peaches':345,'bananas':536}]
>>> [item['apples'] for item in f if isinstance(item, dict) and 'apples' in item]
[430, 123]
If I understand correctly, you want to retrieve the values of multiple dictionaries in the list. This can be done by using a list comprehension to iterate through the list and retrieve the values specified by the key, given that the list element is a dictionary.
Below is a lambda function that works on your list and returns the values stored at 'apples' as a list.
finder = lambda l, string: [x[string] for x in l if type(x) == dict]
print(finder(f, 'apples')) # [430, 123]
print(finder(f, 'peaches')) # [239, 345]

creating a dic from a list of tuples where key takes a list of all available values in python3

this is my code:
mylist=[('joe',120),('john',160),('abraham',250),('soo',250)]
dic={}
for i in mylist:
if i[1] in dic:
dic[i[1]].append(i[0])
else:
dic[i[1]]=i[0]
print(dic)
I expect:
dic={'120':['joe'], '160':['john'], '250':['abraham','soo']}
but I get this error:
dic[i[1]].append(i[0])
AttributeError: 'str' object has no attribute 'append'
When i[1] is not in the dictionary, you need to create a list object. Instead you are assigning just the string to that key:
dic[i[1]]=i[0]
If you wrap that in a list display your code works:
dic[i[1]] = [i[0]] # a list with i[0] as the only element
You can make your code a lot more readable by using tuple unpacking:
for name, value in mylist:
if value in dic:
dic[value].append(name)
else:
dic[value] = [name]
If you used the dict.setdefault() method you can do away with testing if the key is already there:
for name, value in mylist:
dic.setdefault(value, []).append(name)
Here, dict.setdefault() will set the value to an empty list if the key is not yet present in the dictionary, so that the .append() call will always work.
Another alternative would be to use a collections.defaultdict() object; this takes a factory that'll produce a new value for keys that are not there when you try to acces them; set the factory to list to get the same results:
from collections import defaultdict
dic = defaultdict(list)
for name, value in mylist:
dic[value].append(name)

How to iterate through dict in random order in Python?

How can I iterate through all items of a dictionary in a random order? I mean something random.shuffle, but for a dictionary.
A dict is an unordered set of key-value pairs. When you iterate a dict, it is effectively random. But to explicitly randomize the sequence of key-value pairs, you need to work with a different object that is ordered, like a list. dict.items(), dict.keys(), and dict.values() each return lists, which can be shuffled.
items=d.items() # List of tuples
random.shuffle(items)
for key, value in items:
print key, value
keys=d.keys() # List of keys
random.shuffle(keys)
for key in keys:
print key, d[key]
Or, if you don't care about the keys:
values=d.values() # List of values
random.shuffle(values) # Shuffles in-place
for value in values:
print value
You can also "sort by random":
for key, value in sorted(d.items(), key=lambda x: random.random()):
print key, value
You can't. Get the list of keys with .keys(), shuffle them, then iterate through the list while indexing the original dict.
Or use .items(), and shuffle and iterate that.
import random
def main():
CORRECT = 0
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau',
'Arizona': 'Phoenix', 'Arkansas': 'Little Rock'} #etc... you get the idea of a dictionary
allstates = list(capitals.keys()) #creates a variable name and list of the dictionary items
random.shuffle(allstates) #shuffles the variable
for a in allstates: #searches the variable name for parameter
studentinput = input('What is the capital of '+a+'? ')
if studentinput.upper() == capitals[a].upper():
CORRECT += 1
main()
I wanted a quick way for stepping through a shuffled list, so I wrote a generator:
def shuffled(lis):
for index in random.sample(range(len(lis)), len(lis)):
yield lis[index]
Now I can step through my dictionary d like so:
for item in shuffled(list(d.values())):
print(item)
or if you want to skip creating a new function, here is a 2-liner:
for item in random.sample(list(d.values()), len(d)):
print(item)
As Charles Brunet have already said that the dictionary is random arrangement of key value pairs. But to make it really random you will be using random module.
I have written a function which will shuffle all the keys and so while you are iterating through it you will be iterating randomly. You can understand more clearly by seeing the code:
def shuffle(q):
"""
This function is for shuffling
the dictionary elements.
"""
selected_keys = []
i = 0
while i < len(q):
current_selection = random.choice(q.keys())
if current_selection not in selected_keys:
selected_keys.append(current_selection)
i = i+1
return selected_keys
Now when you call the function just pass the parameter(the name of the dictionary you want to shuffle) and you will get a list of keys which are shuffled. Finally you can create a loop for the length of the list and use name_of_dictionary[key] to get the value.

Categories