Iterating over part of dictionary keys - python

I'm new to Python and I'm wondering how can I iterate over part of the keys in a list of dictionaries.
Suppose I have something like:
OrderedDict([('name', 'Anna'), ('AAA', '15'), ('BBB', '49'), ('CCC', '38')])
OrderedDict([('name', 'Bob'), ('AAA', '31'), ('BBB', '21'), ('CCC', '41')])
etc.
I need to retrieve and iterate over AAA, BBB, CCC (keys, not values), but:
only one time (not repeating for every dict in the list, but once, e.g. only for Anna)
skipping 'name', just those going after
in reality, I have many more of these keys (more than 10), so the question is how to iterate and not hard code it
I'd be very glad if you could help
Thanks a lot!

Just iterate over the first list, and check if it's name so you can skip it.
for key in list_of_dicts[0]:
if key != 'name':
print(key)

You can extract the keys from the first row by using:
keys = (key for key in list_of_dicts[0] if key != 'name')
Now you can iterate through the keys using something like:
for var in keys:
print(var)

I'm not sure if it's the best way, but I'd do it like this:
Dict = OrderedDict([('name', 'Anna'), ('AAA', '15'), ('BBB', '49'), ('CCC', '38')])
keys = [] # keys is an empty list
for i in Dict: # Iterate over all keys in the dictionary
if i != 'name': # Exclude 'name' from the list
keys.append(i) # Append each 'i' to the list
That will get you a list, keys, of each of the keys in Dict, excluding 'name'.
You can now iterate over the keys like this:
for i in keys:
print(i) # Do something with each key
And if you want to iterate over the values as well:
for i in keys:
print(Dict[i]) # Do something with each value

You would use a for loop. Here is an example (I called i since I do not know what you call the argument of that function):
i = [('name', 'Anna'), ('AAA', '15'), ('BBB', '49'), ('CCC', '38')]
for a in range(len(i)):
print(i[a][1])
The above gets the index of a, and inside the tuple (which has 2 elements so 0 or 1) gets the 2nd index.
NOTE:
You might want to make a nested for loop to get the ideals within the tuple.

Here is what you can do:
lst = [{...}, {...}, {...}, {...}, ...]
f = ['name']
for d in lst: # For every dict in the list
for k in d: # For every key in the dict
if k not in f: # If the key is not in the list f
# Do something
f.append(k) # Add that key to f so the program won't iterate through it again
UPDATE
(I just found out that every dict has the same keys, so there's no need to do all this checking):
lst = [{...}, {...}, {...}, {...}, ...]
for d in lst: # For every dict in the list
for k in d: # For every key in the dict
if k != 'name': # If the key is not 'name'
# Do something

Related

How to manipulate the dictionary keys and values

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

Convert a dict to tuple preserving order [duplicate]

This question already has answers here:
Converting dict to OrderedDict
(5 answers)
Closed 5 years ago.
I have a dictionary, this is a example dict it can have any number of fields
{'name': 'satendra', 'occupation': 'engineer', 'age': 27}
How can i convert this to tuple so that it will result ordered list of tuple.
# Expected output
[('name', 'satendra'), ('occupation', 'engineer'), ('age', 27)]
UPDATE
OrderedDict are useful when ordered list of tuple passed to it not for a JSON object, so i guess this is not a duplicate
Like you already understood from the comments, there is no order to preserve since there is no order to begin with. This JSON may arrive from the server in any arbitrary order.
However, if you know the keys you are interested in you can construct the list of tuples yourself.
Note that this code iterates over a separate tuple of keys in a known order. You will have to maintain that tuple manually.
relevant_keys = ('name', 'occupation', 'age')
data = {'occupation': 'engineer', 'age': 27, 'name': 'satendra'}
list_of_tuples = [(key, data[key]) for key in relevant_keys]
print(list_of_tuples)
# [('name', 'satendra'), ('occupation', 'engineer'), ('age', 27)]
Use OrderedDict() as suggested in comments, but correctly:
from collections import OrderedDict
d = OrderedDict([('name', 'satendra'), ('occupation', 'engineer'), ('age', 27)])
You define it as you would like your output to be. Then you use it as you would normal dictionary.
And when you want your list of tuples back, you do:
t = d.items()
You can use this solution when you know what keys to expect and you cannot use OrderedDict():
def sortdict (d, keys=["name", "occupation"]):
mx = len(keys)
def customsortkey (key):
try: return keys.index(key)
except: return mx
kys = sorted(d, key=customsortkey)
return [(key, d[key]) for key in kys]
This function will sort everything in the input dictionary "d" according to the order set by "keys" list. Any item in the dictionary, without its key present in list "keys" will be put to the end of the output in arbitrary order. You can indicate keys that aren't present in the dictionary,
The output will be a list of tuples (key, value) as you require.
This is one of possible solutions and it is far from ideal. I.e. we can start a discussion about its efficiency and overhead. But really, in practice it will work just fine, and will handle any unexpected keys nicely.
More efficient version of this function would be to use a dictionary to denote the order of keys instead of the list. A dictionary having the key in question for a key and an sorting index for its value.
Like this:
def sortdict (d, keys={"name": 0, "occupation": 1}):
mx = len(keys)
kys = sorted(d, key=lambda k: keys.get(k, mx))
return [(key, d[key]) for key in kys]
MyDict = {'name': 'satendra', 'occupation': 'engineer', 'age': 27}
MyList = []
For key in MyDict:
MyList.append( (key,MyDict[key]) )
Now MyList is a list of tuples.

Python: Accessing individual values in a dictionary of a list of tuples [duplicate]

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

Extract different values from list of tuples

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.)

Dictionary of dictionaries in Python?

From another function, I have tuples like this ('falseName', 'realName', positionOfMistake), eg. ('Milter', 'Miller', 4).
I need to write a function that make a dictionary like this:
D={realName:{falseName:[positionOfMistake], falseName:[positionOfMistake]...},
realName:{falseName:[positionOfMistake]...}...}
The function has to take a dictionary and a tuple like above, as arguments.
I was thinking something like this for a start:
def addToNameDictionary(d, tup):
dictionary={}
tup=previousFunction(string)
for element in tup:
if not dictionary.has_key(element[1]):
dictionary.append(element[1])
elif:
if ...
But it is not working and I am kind of stucked here.
If it is only to add a new tuple and you are sure that there are no collisions in the inner dictionary, you can do this:
def addNameToDictionary(d, tup):
if tup[0] not in d:
d[tup[0]] = {}
d[tup[0]][tup[1]] = [tup[2]]
Using collections.defaultdict is a big time-saver when you're building dicts and don't know beforehand which keys you're going to have.
Here it's used twice: for the resulting dict, and for each of the values in the dict.
import collections
def aggregate_names(errors):
result = collections.defaultdict(lambda: collections.defaultdict(list))
for real_name, false_name, location in errors:
result[real_name][false_name].append(location)
return result
Combining this with your code:
dictionary = aggregate_names(previousFunction(string))
Or to test:
EXAMPLES = [
('Fred', 'Frad', 123),
('Jim', 'Jam', 100),
('Fred', 'Frod', 200),
('Fred', 'Frad', 300)]
print aggregate_names(EXAMPLES)
dictionary's setdefault is a good way to update an existing dict entry if it's there, or create a new one if it's not all in one go:
Looping style:
# This is our sample data
data = [("Milter", "Miller", 4), ("Milter", "Miler", 4), ("Milter", "Malter", 2)]
# dictionary we want for the result
dictionary = {}
# loop that makes it work
for realName, falseName, position in data:
dictionary.setdefault(realName, {})[falseName] = position
dictionary now equals:
{'Milter': {'Malter': 2, 'Miler': 4, 'Miller': 4}}

Categories

Resources