accesing data in a dictionary python - python

so i have this code:
dic1 = { "data1":1, "data2":2, "data3":3}
dic2 = { "data1":4, "data2":5, "data3":6}
dic3 = { "data1":7, "data2":8, "data3":9}
data = [dic1, dic3, dic2]
how can i access the data in the dictionaries from a function if the input is the list?
so if i have a for:
for x in data:
if x == "dic1":
print dic1["data1"]
print dic1["data2"]
elif x == "dic2":
print dic2["data1"]
and so on......
that will work but only because i know that those dictionaries exist but if another dictionary is created that method will obviously not work, so how can i do it.

Use
for x in data:
for k, v in x.items():
print k, v
So the key here is to use the items method to access to the dictionary's elements.

The first loop iterates over dictionaries, the second loop iterates over keys of dictionary considered by the first loop. Then you print every element:
for dictionary in data:
for key in dictionary:
print dictionary[key]

Related

Python adding the values

# Initialising list of dictionary
ini_dict = [{'a':5, 'b':10, 'c':90},
{'a':45, 'b':78},
{'a':90, 'c':10}]
# printing initial dictionary
print ("initial dictionary", (ini_dict))
# sum the values with same keys
result = {}
for d in ini_dict:
for k in d.keys():
result[k] = result.get(k,0) + d[k]
print("resultant dictionary : ", (result))
Can someone explain the program line by line
Creating a list of dictionary's
ini_dict = [{'a':5, 'b':10, 'c':90},
{'a':45, 'b':78},
{'a':90, 'c':10}]
Prints out the list with dictionary's
print ("initial dictionary", (ini_dict))
Creates a new dictionary
result = {}
Loop's through the List of dictionarys
for d in ini_dict:
so the first d would be {'a':5, 'b':10, 'c':90}
Loop's through the keys of that dict
for k in d.keys():
-> a, b and c
Creates or gets the same key in the result dict and adds the value from the current key. Default value for a new created key is 0.
result[k] = result.get(k,0) + d[k]
Prints out the result dict
print("resultant dictionary : ", (result))
the first line initialises a list of three dictionaries.
ini_dict = [{'a':5, 'b':10, 'c':90},
{'a':45, 'b':78},
{'a':90, 'c':10}]
next up, the dictionary is printed
print ("initial dictionary", (ini_dict))
finally, a weighted histogram is made of the dictionaries based on the keys of the elements within said dictionaries. This is done in three steps:
iterating over the list of dictionaries to get at each different dictionary.
for d in ini_dict:
remember: ini_dict is a list of dictionaries. when you for-loop over a list, the symbol (here d) becomes each of the dictionaries.
iterating over the keys in the dictionary. The method dict.keys() returns a list of keys, over which can be iterated.
for k in d.keys():
finally, for each key in the dictionary the corresponding key in the result dictionary is modified to add the new value. with result.get(k,0) the value for the key k in the result dictionary is fetched, but 0 is the default value if the key is not present.
result[k] = result.get(k,0) + d[k]
This just replaces the result with the previous result + the value in d.
At the end of this bit of code, the result dictionary has the added value of each of the keys.

How to switch values and keys with python dict?

My input is:
files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'
}
I want the output as:
{'Randy':['Input.txt','Output.txt'], 'Stan':['Code.py']}
Basicly it's the other direction of this switch key and values in a dict of lists
This is what I tried:
dictresult= {}
for key,value in files.items():
dictresult[key]=value
dictresult[value].append(key)
But it doesn't work. I get KeyError: 'Randy'
Here's simple approach where we iterate over keys and values of your original dict files and create list for each value to append to it all keys corresponding to that value.
files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'
}
dictresult= {}
for k, v in files.items():
if v not in dictresult:
dictresult[v] = [k]
else:
dictresult[v].append(k)
print(dictresult) # -> {'Randy': ['Output.txt', 'Input.txt'], 'Stan': ['Code.py']}
There are a few problems with your code.
Let's review:
Firstly, you're getting key error because you're trying to append a value to key that doesn't exist. Why? because in you earlier statement you added a value to dict[key] and now you're trying to access/append dict[value].
dictresult[key]=value
You're assigning value to newly generated key, without any check. every new value will overwrite it.
dictresult[value].append(key)
Then you're trying to append a new value to a string using a wrong key.
You can achieve what you want by the following code:
d = {}
for key,value in files.items():
if value in d:
d[value].append(key)
else:
d[value] = [key]
print(d)
It will output:
{'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}
How/why it works?
Let's review:
The if condition checks if that key is already present in the dictionary. When iterated over a dictionary, it returns it's keys only, not key value pairs unlike dict.items()
If the key is there we simply append the current value to it.
In other case, where that key is not present, we add a new key to dictionary but we do it by casting it to a list, otherwise a string would be inserted as a value, not a list and you won't be able to append to it.
Try using defaultdict -
from collections import defaultdict
dictresult= defaultdict(list)
for key,value in files.items():
dictresult[value].append(key)
This will assume there is an empty list in every item in the dictionary so the append won't fail
You can check if the value as a key exist in dictresult
Like
dictresult= {}
for key,value in files.items():
if not value in dictresult: dictresult [value]=[]
dictresult[value].append(key)
output = {}
for key, value in files.items():
output[value] = output.get(value, []) + [key]
print(output)
# {'Randy':['Input.txt','Output.txt'], 'Stan':['Code.py']}
Here are two ways how you can do it.
from collections import defaultdict
files = {"Input.txt": "Randy", "Code.py": "Stan", "Output.txt": "Randy"}
expected = {"Randy": ["Input.txt", "Output.txt"], "Stan": ["Code.py"]}
# 1st method. Using defaultdict
inverted_dict = defaultdict(list)
{inverted_dict[v].append(k) for k, v in files.items()}
assert inverted_dict == expected, "1st method"
# 2nd method. Using regular dict
inverted_dict = dict()
for key, value in files.items():
inverted_dict.setdefault(value, list()).append(key)
assert inverted_dict == expected, "2nd method"
print("PASSED!!!")

want to find a matching variable from multi key possibly tuples in dict and print the value in python

How can i search a variable from a multi key dict and get the respective value in python?
dict1 = {('1700','2700','3700'):'a3g3',('1502','1518'):'a2g3',('2600'):'a3g2'}
var = '1502'
output
should be a2g3
One way:
dict1 = {('1700','2700','3700'): 'a3g3',
('1502','1518'): 'a2g3',
('2600'): 'a3g2'}
print(next(v for k, v in dict1.items() if '1502' in k))
# a2g3
List comprehension is good approach ,
Here is Filter approach just for fun :
You can filter the result :
dict1 = {('1700','2700','3700'):'a3g3',('1502','1518'):'a2g3',('2600'):'a3g2'}
var = '1502'
print(dict1[list(filter(lambda x:var in x,dict1.keys()))[0]])
output:
a2g3
Just iterate over the keys and find
print([dict1[i] for i in dict1.keys() if var in i])

Create a new dict of first n values (and keys) from dictionary - Python

I have a dictionary:
{'my_account': [45010045, 43527907, 45147474, 35108100, 45159973],
'your_account': [38966628, 28171579, 39573751, 41359842, 42445236],
'his_account': [44822460, 45010045, 39276850, 39896128, 45265335]
}
I want to keep the first 2 elements of every key, so the result would look like:
{'my_account': [45010045, 43527907],
'your_account': [38966628, 28171579],
'his_account': [44822460, 45010045]
}
Is there any way to achieve this? Thanks.
using dictionary comprehension
my_dict = {'my_account': [45010045, 43527907, 45147474, 35108100, 45159973],
'your_account': [38966628, 28171579, 39573751, 41359842, 42445236],
'his_account': [44822460, 45010045, 39276850, 39896128, 45265335]
}
new_dict = {k:v[:2] for k,v in my_dict.items()}
# {'my_account': [45010045, 43527907], 'your_account': [38966628, 28171579], 'his_account': [44822460, 45010045]}
Just slice-delete the values.
for v in D.itervalues():
del v[2:]

Nested lists to nested dicts

I've a list with master keys and a list of list of lists, where the first value of each enclosed list (like 'key_01') shall be a sub key for the corresponding values (like 'val_01', 'val_02'). The data is shown here:
master_keys = ["Master_01", "Master_02", "Master_03"]
data_long = [[['key_01','val_01','val_02'],['key_02','val_03','val_04'], ['key_03','val_05','val_06']],
[['key_04','val_07','val_08'], ['key_05','val_09','val_10'], ['key_06','val_11','val_12']],
[['key_07','val_13','val_14'], ['key_08','val_15','val_16'], ['key_09','val_17','val_18']]]
I would like these lists to be combined into a dictionary of dictionaries, like this:
master_dic = {
"Master_01": {'key_01':['val_01','val_02'],'key_02': ['val_03','val_04'], 'key_03': ['val_05','val_06']},
"Master_02": {'key_04': ['val_07','val_08'], 'key_05': ['val_09','val_10'], 'key_06': ['val_11','val_12']},
"Master_03": {'key_07': ['val_13','val_14'], ['key_08': ['val_15','val_16'], 'key_09': ['val_17','val_18']}
}
What I've got so far is the sub dict:
import itertools
master_dic = {}
servant_dic = {}
keys = []
values = []
for line in data_long:
for item in line:
keys.extend(item[:1])
values.append(item[1:])
servant_dic = dict(itertools.izip(keys, values))
Which puts out a dictionary, as expected.
servant_dic = {
'key_06': ['val_11','val_12'], 'key_04': ['val_08','val_07'], 'key_05': ['val_09','val_10'],
'key_02': ['val_03','val_04'], 'key_03': ['val_05','val_06'], 'key_01': ['val_01','val_02']
}
The problem is, that if I want to add the master_keys to this dictionary, so I get the wanted result, I'd have to do this in a certain order, which would be possible, if each line had a counter like this:
enumerated_dic =
{
0: {'key_01':['val_01','val_02'],'key_02': ['val_03','val_04'], 'key_03': ['val_05','val_06']},
1: {'key_04': ['val_07','val_08'], 'key_05': ['val_09','val_10'], 'key_06': ['val_11','val_12']},
2: {'key_07': ['val_13','val_14'], ['key_08': ['val_15','val_16'], 'key_09': ['val_17','val_18']}
}
I'd love to do this with enumerate(), while each line of the servant_dic is build, but can't figure out how. Since afterwards, i could simply replace the counters 0, 1, 2 etc. with the master_keys.
Thanks for your help.
master_keys = ["Master_01", "Master_02", "Master_03"]
data_long = [[['key_01','val_01','val_02'],['key_02','val_03','val_04'], ['key_03','val_05','val_06']],
[['key_04','val_07','val_08'], ['key_05','val_09','val_10'], ['key_06','val_11','val_12']],
[['key_07','val_13','val_14'], ['key_08','val_15','val_16'], ['key_09','val_17','val_18']]]
_dict = {}
for master_key, item in zip(master_keys, data_long):
_dict[master_key] = {x[0]: x[1:] for x in item}
print _dict
Hope this will help:
{master_key: {i[0]: i[1:] for i in subkeys} for master_key, subkeys in zip(master_keys, data_long)}
My functional approach:
master_dic = dict(zip(master_keys, [{k[0]: k[1::] for k in emb_list} for emb_list in data_long]))
print(master_dic)
You can also use pop and a dict comprehension:
for key, elements in zip(master_keys, data_long):
print {key: {el.pop(0): el for el in elements}}
...:
{'Master_01': {'key_02': ['val_03', 'val_04'], 'key_03': ['val_05', 'val_06']}}
{'Master_02': {'key_06': ['val_11', 'val_12'], 'key_04': ['val_07', 'val_08'], 'key_05': ['val_09', 'val_10']}}
{'Master_03': {'key_07': ['val_13', 'val_14'], 'key_08': ['val_15', 'val_16'], 'key_09': ['val_17', 'val_18']}}

Categories

Resources