How to extract a list of different values from following list of tuples?
tuple = ((("test", 123), ("test", 465), ("test", 8910), ("test2", 123)))
I want to get a list like:
different_values = ("test", "test2")
Now I want to access all values by this "keys" and get them by a list:
test_values = (123, 456, 8910)
test2_values = (123)
How to do that?
I'd transform your data to a dictionary of lists:
d = {}
for k, v in tuples:
d.setdefault(k, []).append(v)
Now you can access the keys as d.keys(), and the list of values for each key k as d[k].
(Shortly, someone will step forward and claim a defaultdict would be better for this. Don't listen to them, it simply doesn't matter in this case.)
Related
In Python, how can we assign multiple dictionary keys the same value.
I tried something below but it's not working.
server = {'server1','server2': 'abc#xyz.com', 'server3','server4':'pqr#xyz.com'}
For example:
s = "the_value" # the value you want for the keys below
l = ["name", "age", "address"] # keys
d = {} # initiating an empty dictionary
for item in l:
d[item] = s
This should print
{'name': 'the_value', 'age': 'the_value', 'address': 'the_value'}
If you order your inputs as list of tuples, where each tuple is the value and a list of servers, you can use a nested list comprehension to create your dictionary:
from pprint import pprint
# arange your inputdata as tuples of ("value" to be set, list of servers)
# data = [ (f"login_{v}",[f"server_{v}{10+w}" for w in range(3)]) for v in range(5)]
data = [ ('login_0', ['server_010', 'server_011', 'server_012']),
('login_1', ['server_110', 'server_111', 'server_112']),
('login_2', ['server_210', 'server_211', 'server_212']),
('login_3', ['server_310', 'server_311', 'server_312']),
('login_4', ['server_410', 'server_411', 'server_412']) ]
# create the dict using a nested list comprehension
d = {k:v for v,keys in data for k in keys}
pprint(d)
Output:
# of the created dict using a nested list comprehension
{'server_010': 'login_0',
'server_011': 'login_0',
'server_012': 'login_0',
'server_110': 'login_1',
'server_111': 'login_1',
'server_112': 'login_1',
'server_210': 'login_2',
'server_211': 'login_2',
'server_212': 'login_2',
'server_310': 'login_3',
'server_311': 'login_3',
'server_312': 'login_3',
'server_410': 'login_4',
'server_411': 'login_4',
'server_412': 'login_4'}
See Explanation of how nested list comprehension works? if you do not know about those.
You could use tuples as keys but then it is difficult to find the dictionary entry corresponding to a single value
server = {('server1','server2','serverX'): 'abc#xyz.com', \
('server3','server4'):'pqr#xyz.com'}
Note: you can do that because tuples are hashable.
This makes only sense if you want to query the dictionary by exactly such tuples, for instance:
server[('server3', 'server4')]
# Out: 'pqr#xyz.com'
I have a dictionary and I want to change the key of the dictionary into a unique value.
final_dict = {"name1":['raj','raj','raj'],"name2":['Rahul','Thor','max','Rahul'],"name3":['Jhon','Jhon'], "name4":['raj','raj'], "name5":['Rahul','Thor','max']}
First of all, I need unique values for each key like this
final_dict = {"name1":['raj'],"name2":['Thor','max','Rahul'],"name3":['Jhon'], "name4":['raj'], "name5":['Rahul','Thor','max']}
and then I need to convert the keys as values and vales as key
the final output I needed
output = {"raj":['name1','name4'], "('Thor','max','Rahul')":[name2,name5], "jhon":[name3]}
I tried this but I got only the unique values
mtype=[]
for key_name in final_dict:
a = set(final[key_name])
#print(tuple(a))
mtype.append(tuple(a))
print(mtype)
u = set(mtype)
print(u)
Here's a first shot at the problem. I'd carefully read through each line and make sure you understand what is going on. Feel free to ask follow ups in the comments!
from collections import defaultdict
input = { ... }
output = defaultdict(list)
for key, values in input.items():
unique_values = tuple(sorted(set(values)))
output[unique_values].append(key)
output = dict(output) # Transform defaultdict to a dict
Here is a straight forward way -
The set() takes care of the unique and the list comprehension below changes the dict items to item, key tuples.
dict.setdefault() allows appending each of the tuples into a blank list [] (key, value) pairs where the same key gets a list of values.
d = {}
l = [(i,k) for k,v in final_dict.items() for i in set(v)]
#print(l)
#[('raj', 'name1'), ('Thor', 'name2'), ('max', 'name2'), ('Rahul', 'name2'),
#('Jhon', 'name3'), ('raj', 'name4'), ('Thor', 'name5'), ('max', 'name5'),
#('Rahul', 'name5')]
for x, y in l:
d.setdefault(x, []).append(y)
print(d)
{'Jhon': ['name3'],
'Rahul': ['name2', 'name5'],
'Thor': ['name2', 'name5'],
'max': ['name2', 'name5'],
'raj': ['name1', 'name4']}
This question already has answers here:
Query Python dictionary to get value from tuple
(3 answers)
Closed 6 years ago.
I have a dictionary in Python where each key has a set of ten tuples. I am trying to iterate through the dictionary access the individual elements within each tuple- how should I go about that?
The dictionary looks like this:
{'Key1': [(Hi, 1), (Bye, 2)], 'Key2': [(Cats, Blue), (Dogs, Red)]}
Say I want vectors of the Keys, a vectors of the first elements [Hi, Bye, Cats, Dogs] and one of the second [1,2, Blue, red]
This is the code I was attempting:
for key in dict:
for tuplelist in dict:
key_vector.append(key_
tuple1_vector.append(dict[key[1]])
tuple2_vector.append(dict[key[2]])
I know this is incorrect but I am not sure how to go about fixing it.
I assume you mean your dict is:
your_dict = {'Key1': [('Hi', 1), ('Bye', 2)], 'Key2': [('Cats', 'Blue'), ('Dogs', 'Red')]}
You can iterate over all the keys, get whatever tuple is in there, and then iterate over all the entries inside that tuple. There probably is an easier way but this should at least get you there:
for key in your_dict:
for t in your_dict[key]:
for i in t:
print(i)
You can use .values() to access the values in the dictionary, then iterate over the values lists and index the respective items in the tuple:
tuple1_vector = []
tuple2_vector = []
for v in d.values():
for t in v:
tuple1_vector.append(t[0])
tuple2_vector.append(t[1])
You can also do this with a list comprehension:
tuple1_vector = [t[0] for v in d.values() for t in v]
tuple2_vector = [t[1] for v in d.values() for t in v]
print(tuple1_vector)
# ['Cats', 'Dogs', 'Hi', 'Bye']
print(tuple2_vector)
# ['Blue', 'Red', 1, 2]
You could do the following:
keys = []
tuple1 = []
tuple2 = []
for key in dict:
keys.append(key)
tuple1.append(dict[key][0][0])
tuple1.append(dict[key][0][1])
tuple1.append(dict[key][1][0])
tuple1.append(dict[key][1][1])
But do not, this is really bad code. I'm just showing a solution but that's not worth it. The other guys have made it better (such as iterating over dict[key] (e.g. for item in dict[key]...) .
I've got a list k with the 0'th element:
k[0]: {'pattern': 0, 'pos': array([ 9.83698, 106.539 , 130.314 ]), 'id': 1922}
(It looks like a dict, but its a list indeed)
when I iterate through the 0'th element of the list k and print out each element I Get:
for i in k:
print i
=>output:
pattern
pos
id
I'd like to access not only the keys but the values as well. How to do this?
I've also tried to convert the list back into a dict using zip and izip, but same resutlts...i.e. only keys are printed, no values...
any help will be appreciated
thx in advance
you can use k.values() to iterate through the values, or k.items() to iterate through (key, value) pairs
for value in k.values():
print value
for key, value in k.items():
print key, value
The fastest way to iterate over the dictionary you created (it is in fact a dictionary) is not to create the lists of keys/values using k[0].keys(), k[0].values and k[0].items() but using k[0].iteritems() which creates a dictionary iterator that returns just the pairs without allocating lists in the memory.
It also runs much faster for big dictionaries (a being the dictionary):
>>> non_iter_timer = timeit.Timer("for k,v in a.items(): k + v", setup="a = {x:x for x in xrange(10000000)}")
>>> non_iter_timer.repeat(3, 10)
[25.612606023166585, 25.100741935717622, 24.840450306339463]
>>> iter_timer = timeit.Timer("for k,v in a.iteritems(): k + v", setup="a = {x:x for x in xrange(10000000)}")
>>> iter_timer.repeat(3, 10)
[9.26259596885518, 9.198298194571748, 9.77466250122282]
Say I have a list of list like this: (suppose you have no idea how many lists in this list)
list=[['food','fish'],['food','meat'],['food','veg'],['sports','football']..]
how can I merge the items in the list like the following:
list=[['food','fish','meat','veg'],['sports','football','basketball']....]
i.e, merge all the nested lists into the same list if they contain one of the same items.
Use defaultdict to make a dictionary that maps a type to values and then get the items:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> items = [['food','fish'],['food','meat'],['food','veg'],['sports','football']]
>>> for key, value in items:
... d[key].append(value)
...
>>> [[key] + values for key, values in d.items()]
[['food', 'fish', 'meat', 'veg'], ['sports', 'football']]
The "compulsory" alternative to defaultdict which can work better for data that's already in order of the key and if you don't want to build data structures on it (ie, just work on groups)...
data = [['food','fish'],['food','meat'],['food','veg'],['sports','football']]
from itertools import groupby
print [[k] + [i[1] for i in v] for k, v in groupby(data, lambda L: L[0])]
But defaultdict is more flexible and easier to understand - so go with #Blender's answer.