Dict into Dict Python - python

I am new in Python, Currently I am working data dictionary.
I expect to create dict into dict like this:
dates = {201101:{perf:10, reli:20, qos:300}, 201102:{perf:40, reli:0, qos:30}}
I already have the keys, and I have to created default values for initialization. i.e:
{201101:{perf:0, reli:0}, 201102:{perf:0, reli:0}}
how to do initiation and update the specifict dict. ie dates[201101[perf]] = 10.
Thanks!

To begin with
dates = {201101{perf=10, reli=20, qos=300}, 201102{perf=40, reli=0, qos=30}}
is not a valid python dict. This is:
dates = {201101: {'perf':10, 'reli':20, 'qos':300}, 201102:{'perf':40, 'reli':0, 'qos':30}}
Once you have initiated the dict of dict as:
dates = {201101:{'perf':0, 'reli':0}, 201102:{'perf':0, 'reli':0}}
you update it by doing:
dates[201101]['perf'] = 10
Demo:
>>> dates = {201101:{'perf':0, 'reli':0}, 201102:{'perf':0, 'reli':0}}
>>> dates[201101]['perf'] = 10
>>> dates
{201101: {'reli': 0, 'perf': 10}, 201102: {'reli': 0, 'perf': 0}}

First, you need to separate keys from their values with a :. Secondly, your keys need to be strings or numbers. Example.
dates = { 201101: {'perf': 10, 'reli':20, 'qos': 300} }

Your first dict:
dates={201101:{'perf':0, 'reli':0}, 201102:{'perf':0, 'reli':0}}
One way to update key's value:
date[201101]={'perf': 10, 'reli':20, 'qos': 300}

Another Method that you would need in case of run-time values is setdefault(i,[]) or {} instead of []. This allows you to dynamically create nested dictionaries instead of "flat".
For example:
dict = {}
for i in range(0,10):
dict.setdefault(i,{})
# Only now you can use the nested dict of level 1
for j in range(0,10):
dict[i][j] = j
This is just an example, you can dynamically create dict of any deep and with heterogeneous elements as list or other dict.

Related

Python create multiple dictionaries from values ​read from a list

I have the following list of values: Numbers = [1,2,3,4].
Is it possible to create a dictionary with the same name as the values ​​contained in the list?
Example: dictionary_1 = {}
dictionary_2 = {}
....
dictionary_Number.. {}
I would like to create these dictionaries automatically, without creating them manually, reading the numbers contained in the list
You may use the keyword exec in python. Here is an example of your solution,
List = [1, 2,3]
for ele in List:
dic = f"Dictionary_{ele}"
exec(dic+" = {}")
print(Dictionary_1, Dictionary_2, Dictionary_3, sep='\n')
you may use it according to you, but the disadvantage for it is that you will need to use exec every time you need to use it or you must know what would be the name outcome of the first use of exec ...
I hope I helped...
Use the inbuild functions and remember that a dictionary needs a tuble (key & value):
Python Dictionaries
Python Dictionary fromkeys() Method
Example-Code:
Numbers = [1,2,3,4]
Numbers_dict = dict.fromkeys(Numbers,"dict_value")
print(Numbers_dict)
This will output:
{'1': 'dict_value', '2': 'dict_value', '3': 'dict_value', '4': 'dict_value'}
If you want to get a single dictonaries for each list-value, you first have to create for each list-value an empty variable.
After this you have to fill this empty vairables within a loop.

convert python list into dictionary with key only , no value

I have a list of room names in python, however I need it to be a dictionary, simply in the form {"room1", "room2", "room3"}
Currently, my code can take the list and turn to a dictionary with both values and keys, i.e. {"room1":0, "room2":1, "room3": 2} etc.
my code is as follows:
rooms = ["G5a", "G5b", "G11"]
roomdict = dict(zip(rooms,range(len(rooms))))
print(roomdict)
But, this is not the format I need my dictionary to be in - thanks for your help in advanace :)
What you need is a set:
A set is an unordered collection of items. Every element is unique (no duplicates) and must be immutable (which cannot be changed).
rooms = ["G5a", "G5b", "G11"]
print(set(rooms))
OUTPUT:
{'G5b', 'G5a', 'G11'}
On the odd chance that your really need a dict with keys and empty values:
mydict = {"room1" : None, "room2": None, "room3" : None}
You could use the dict.fromkeys() method:
rooms = ["G5a", "G5b", "G11"]
roomdict = dict.fromkeys(rooms, None)
print(roomdict)
Output:
{'G5b': None, 'G11': None, 'G5a': None}

Python: add to a dictionary in a list

I have the following dictionary (It is for creating json),
temp = {'logs':[]}
I want to append dictionaries, but i only got 1 key:val at a time.
what I tried:
temp['logs'].append({key:val})
This does as expected and appends the dict to the array.
But now I want to add a key/val pair to this dictionary, how can I do this?
I've tried using append/extend but that just adds a new dictionary to the list.
But now I want to add a key/val pair to this dictionary
You can index the list and update that dictionary:
temp['logs'][0].update({'new_key': 'new_value'})
You can use this command to change your dict values :
>>> temp['logs'][0]={'no':'val'}
>>> temp
{'logs': [{'no': 'val'}]}
And this one to add values :
>>> temp['logs'][0].update({'yes':'val'})
>>> temp
{'logs': [{'key': 'val', 'yes': 'val'}]}
There must be unique "key" every time you append it. (If it is for json)
Also making "=" will update your old dictionary
What I have done when I was stuck once is
user = {}
name,password,id1 = [],[],[]
user1=session.query(User).all()
for i in user1:
name=i.name
password=i.password
id1=i.id
user.update({ id1:{
"name" : name,
"password" : password,
}
})
check this link might be helpful to you
How to convert List of JSON frames to JSON frame
Note that adding a dictionary (or any object) to a list only stores a reference, not a copy.
You can therefor do this:
>>> temp = {'logs': []}
>>> log_entry = {'key1': 'val1'}
>>> temp['logs'].append(log_entry)
>>> temp
{'logs': [{'key1': 'val1'}]}
>>> log_entry['key2'] = 'val2'
>>> temp
{'logs': [{'key2': 'val2', 'key1': 'val1'}]}
However, you might be able to circumvent to whole issue by using dict comprehension (only in Python >=2.7)
>>> temp = {'logs': [{key: value for key, value in my_generator}]
Try this example:
temp = {
'logs':[]
}
[temp['logs'].append(log) for log in errors['logs']]
Your log data would be list with multiple dictionary

Initializing a dictionary in python with a key value and no corresponding values

I was wondering if there was a way to initialize a dictionary in python with keys but no corresponding values until I set them. Such as:
Definition = {'apple': , 'ball': }
and then later i can set them:
Definition[key] = something
I only want to initialize keys but I don't know the corresponding values until I have to set them later. Basically I know what keys I want to add the values as they are found. Thanks.
Use the fromkeys function to initialize a dictionary with any default value. In your case, you will initialize with None since you don't have a default value in mind.
empty_dict = dict.fromkeys(['apple','ball'])
this will initialize empty_dict as:
empty_dict = {'apple': None, 'ball': None}
As an alternative, if you wanted to initialize the dictionary with some default value other than None, you can do:
default_value = 'xyz'
nonempty_dict = dict.fromkeys(['apple','ball'],default_value)
You could initialize them to None.
you could use a defaultdict. It will let you set dictionary values without worrying if the key already exists. If you access a key that has not been initialized yet it will return a value you specify (in the below example it will return None)
from collections import defaultdict
your_dict = defaultdict(lambda : None)
It would be good to know what your purpose is, why you want to initialize the keys in the first place. I am not sure you need to do that at all.
1) If you want to count the number of occurrences of keys, you can just do:
Definition = {}
# ...
Definition[key] = Definition.get(key, 0) + 1
2) If you want to get None (or some other value) later for keys that you did not encounter, again you can just use the get() method:
Definition.get(key) # returns None if key not stored
Definition.get(key, default_other_than_none)
3) For all other purposes, you can just use a list of the expected keys, and check if the keys found later match those.
For example, if you only want to store values for those keys:
expected_keys = ['apple', 'banana']
# ...
if key_found in expected_keys:
Definition[key_found] = value
Or if you want to make sure all expected keys were found:
assert(all(key in Definition for key in expected_keys))
You can initialize the values as empty strings and fill them in later as they are found.
dictionary = {'one':'','two':''}
dictionary['one']=1
dictionary['two']=2
Comprehension could be also convenient in this case:
# from a list
keys = ["k1", "k2"]
d = {k:None for k in keys}
# or from another dict
d1 = {"k1" : 1, "k2" : 2}
d2 = {k:None for k in d1.keys()}
d2
# {'k1': None, 'k2': None}
q = input("Apple")
w = input("Ball")
Definition = {'apple': q, 'ball': w}
Based on the clarifying comment by #user2989027, I think a good solution is the following:
definition = ['apple', 'ball']
data = {'orange':1, 'pear':2, 'apple':3, 'ball':4}
my_data = {}
for k in definition:
try:
my_data[k]=data[k]
except KeyError:
pass
print my_data
I tried not to do anything fancy here. I setup my data and an empty dictionary. I then loop through a list of strings that represent potential keys in my data dictionary. I copy each value from data to my_data, but consider the case where data may not have the key that I want.

Python dictionary : TypeError: unhashable type: 'list'

I'm having troubles in populating a python dictionary starting from another dictionary.
Let's assume that the "source" dictionary has string as keys and has a list of custom objects per value.
I'm creating my target dictionary exactly as I have been creating my "source" dictionary how is it possible this is not working ?
I get
TypeError: unhashable type: 'list'
Code :
aTargetDictionary = {}
for aKey in aSourceDictionary:
aTargetDictionary[aKey] = []
aTargetDictionary[aKey].extend(aSourceDictionary[aKey])
The error is on this line : aTargetDictionary[aKey] = []
The error you gave is due to the fact that in python, dictionary keys must be immutable types (if key can change, there will be problems), and list is a mutable type.
Your error says that you try to use a list as dictionary key, you'll have to change your list into tuples if you want to put them as keys in your dictionary.
According to the python doc :
The only types of values not acceptable as keys are values containing
lists or dictionaries or other mutable types that are compared by
value rather than by object identity, the reason being that the
efficient implementation of dictionaries requires a key’s hash value
to remain constant
This is indeed rather odd.
If aSourceDictionary were a dictionary, I don't believe it is possible for your code to fail in the manner you describe.
This leads to two hypotheses:
The code you're actually running is not identical to the code in your question (perhaps an earlier or later version?)
aSourceDictionary is in fact not a dictionary, but is some other structure (for example, a list).
As per your description, things don't add up. If aSourceDictionary is a dictionary, then your for loop has to work properly.
>>> source = {'a': [1, 2], 'b': [2, 3]}
>>> target = {}
>>> for key in source:
... target[key] = []
... target[key].extend(source[key])
...
>>> target
{'a': [1, 2], 'b': [2, 3]}
>>>
It works fine : http://codepad.org/5KgO0b1G,
your aSourceDictionary variable may have other datatype than dict
aSourceDictionary = { 'abc' : [1,2,3] , 'ccd' : [4,5] }
aTargetDictionary = {}
for aKey in aSourceDictionary:
aTargetDictionary[aKey] = []
aTargetDictionary[aKey].extend(aSourceDictionary[aKey])
print aTargetDictionary
You can also use defaultdict to address this situation. It goes something like this:
from collections import defaultdict
#initialises the dictionary with values as list
aTargetDictionary = defaultdict(list)
for aKey in aSourceDictionary:
aTargetDictionary[aKey].append(aSourceDictionary[aKey])

Categories