Python - Accessing values from a dictionary - python-3.x

Working on something for fun...completely new to programming. How do I access the values in the dictionary so I can either add the cost values or check if its a "Main" or "Side" item, etc.
from collections import OrderedDict
#Items on menu
item1 = OrderedDict(name = "Regular Pizza",
cost = 20,
item_type = "Main",
size = "Regular")
item2 = OrderedDict(name = "Regular Salad",
cost = 5,
item_type = "Side",
size = "Regular")

Well, first things first.
I see that you are using OrderedDict from collections instead of just using dict. Don't do it, as you are new to Dictionary you should start from "vanilla dict" in my opinion.
OrderedDict as the name suggests is meant to preserve the order of the elements inside it.
But, after Python 3.5 the order preservation feature was implemented to dict, read more in this answer - Difference between dict and ordered dict
Also, as we access the dictionary values by their key, i don't think the order has much use here.
Now for your question on how to access the dictionary elements. Going from your example you have 2 items in the menu.
item1 = {
'name' : 'Regular Pizza',
'cost' : 20,
'item_type' : 'Main',
'size' : 'Regular'
}
item2 = {
'name' : 'Regular Salad',
'cost' : 5,
'item_type' : 'Side',
'size' : 'Regular'
}
Here i have created a dictionary with 2 items. Now
Check if the dish is main or not.
print ('The item is a ' + item1['item_type']+ ' dish')
Adding cost to items.
# increase item1 cost by 5
item1['cost'] += 5
Tip: Further you can put all the dishes inside a list and access them directly by the index values, with that you won't have to create multiple variables such as item1, item2...
The implemention would be like-
food = [
{ 'name' : 'Regular Pizza',
'cost' : 20,
'item_type' : 'Main',
'size' : 'Regular'}
,
{ 'name' : 'Regular Salad',
'cost' : 5,
'item_type' : 'Side',
'size' : 'Regular'}
]
Now to access the elements-
print ('The item is a ' + food[0]['item_type']+ ' dish')
food[0]['cost'] += 5

Related

Count number of keys in ordered dict that start with specific string

I'd like to count the number of strings in an ordered dict that start with a particular string.
For example, I have the following ordered dict:
OrderedDict([('Name', 'First'), ('Size': '10'), ('Rate 1', '1000'), ('Rate 2', '100'), ('End', 'Last'])
I want to count the number of keys that start with "Rate". In this example, it would be 2.
I tried n = len(o_dict.keys().startswith('Rate')) with but this results in AttributeError: 'odict_keys' object has no attribute 'startswith'.
Any idea what to do here? Thanks in advance.
from collections import OrderedDict
od = OrderedDict([('Name', 'First'), ('Size', '10'), ('Rate 1', '1000'), ('Rate 2', '100'), ('End', 'Last')])
cnt = sum([1 for key in od.keys() if key.startswith("Rate")])
print(cnt)
Output
2

How to use eval in nested dictionary in Python

I have a dictionary similar to the below structure
sample_dict = {
'key1' : 'getVal1' ,
'key2' : 'getVal2' ,
'level1' :
{
'key3' : 'getVal3' ,
'level2' :
{
'key4' : 'getVal4'
}
}
}
I want to evaluate entire dictionary without accessing individual inner dict separately. (Eg : Without accessing 'level1' and 'level2' keys.)
The values are separate functions.. example is mentioned below.
def getVal1():
return "Some Calculation"
If it was a simple dict without nesting, it would be very simple to process, something like below.
final_dict = {k : eval(v) for k,v in sample_dict .items()}
But with nested dictionary, I am not able to construct.
If there is any generic way for this, it will be really helpful.

Inputting data to a dictionary(perhaps from a file) with nested lists as the values

All, I need to find an effective way to input my data into my script to end up with a dictionary that looks like so:
CSSes_2_add = {
'Test CSS 1': ['Test CSS 1',['Staging','On Cluster','Test9','Test8', 'Test7', 'Test6', 'Test5',]],
'Test CSS 2': ['Test CSS 2',['On Cluster','Staging','Test1','Test2', 'Test3', 'Test4', 'Test5']],
'Auto Registered Devices': ['For Auto Registered Device Templates' ,['Block Toll Fraud']]
}
Please note that the number of elements of: `CSSes_2_add[x][1] will be different for each key of the dictionary. Instead of hardcoding my dictionary into my script, I'd like to know of a more efficient way to input my data. Please help
P.S.
If the suggestion is CSV, how do I handle the varying number of elements of the nested list.
Just using the data you have listed above an easy way of doing what you want is to loop through all the keys and data.
keys = ['Test CSS 1', 'Test CSS 2', 'Auto Registered Devices']
data_keys = ['Test CSS 1','Test CSS 2','For Auto Registered Device Templates']
d1 = ['Staging','On Cluster','Test9','Test8', 'Test7', 'Test6', 'Test5']
d2 = ['On Cluster','Staging','Test1','Test2', 'Test3', 'Test4', 'Test5']
d3 = ['Block Toll Fraud']
allData = [d1,d2,d3]
d = {}
for key, data_key in zip(keys, data_keys):
d[key] = [data_key]
for key, data in zip(list(d.keys()), allData):
d[key].append(data)
This will get you what you asked for, but if you are planning on accessing data from this dictionary it might get a little messy having to run through the nested list indexes.
I solved my problem with DictReader:
I have a CSV input file named "addCss.csv" with the following contents:
CssName,CssDesc,Partition1,Partition2,Partition3,Partition4,Partition5,Partition6,Partition7,Partition8,Partition9,Partition10,Partition11,Partition12,Partition13,Partition14,Partition15
CSS1,Description for CSS1,On Net,Staging,,,,,,,,,,,,,
CSS2,Description for CSS2, Test1, Test3, Test5,,,,,,,,,,,,
CSS3,Description for CSS3, Partition1, Test9, Test6,,,,,,,,,,,,
I then loop through the file and add the data to my dictionary as follows:
with open('addCss.csv', newline='') as css_csv_file:
css_csv_reader = csv.DictReader(css_csv_file)
CSSes_2_add = {}
for css_row in css_csv_reader:
css_input_outer_list = []
css_input_nested_list = []
css_input_outer_list.append(css_row['CssDesc'])
CSSes_2_add[css_row['CssName']] = css_input_outer_list
for N in range(1,15):
n = str(N)
if css_row['Partition'+n] != '':
css_input_nested_list.append(css_row['Partition'+n])
css_input_outer_list.append(css_input_nested_list)
print(CSSes_2_add)

Python updating dictionary but need to get the key pair?

Given this dictionary format:
name: (id, type1, type2, hp, attack, defense, speed, generation, legendary)
dict={'Bulbasaur': (1, 'Grass', 'Poison', 45, 49, 49, 45, 1, False)}
I need to go through the database (dictionary of multiple pokemon with their stats in the provided format) and find which pokemon have legendary status, which is a boolean value. I need to count the types that are legendary and put them in a new dictionary.
So for example if Bulbasaur was legendary, Grass type=1 Poison type=1. New dictionary item would be :
new_dict={"Grass": 1, "Poison": 1}
I made the code to get the types extracted and then count which types are legendary but I am stuck on how to get the final dictionary with type and count number.
Here is the code that I have:
def legendary_count_of_types(db):
Fire=0
Grass=0
Flying=0
Poison=0
Dragon=0
Water=0
Fighting=0
Ground=0
Ghost=0
Rock=0
Ice=0
d={}
for key,values in db.items():
status=values[8]
if status==True:
type_list=get_types(db)
for item in type_list:
if item=='Fire':
Fire+=1
if item=='Grass':
Grass+=1
if item=='Flying':
Flying+=1
if item=='Poison':
Poison+=1
if item=='Dragon':
Dragon+=1
if item=='Water':
Water+=1
if item=='Fighting':
Fighting+=1
if item=='Ground':
Ground+=1
if item=='Ghost':
Ghost+=1
if item=='Rock':
Rock+=1
if item=='Ice':
Ice+=1
d.update()
#how do I get the key value pair?
return d
Here is what my get_types function does:
def get_types(db):
l=[]
s=[]
for key,values in db.items():
types1=str(values[1])
types2-str(values[2])
l.apppend(types1)
l.append(types2)
for i in l:
if i not in s:
s.append(i)
if 'None' in s:
s.remove('None')
final_list=s
return sorted(final_list)
Assuming you just want a count of the times a type appears in a legendary Pokemon, without using anything fancy like pandas (which you probably ought to be doing with your data collection, or maybe a little sql db)
type_counter = dict() # or use collections.Counter
for name, attributes in db.items()
is_legendary = attributes[8]
if is_legendary:
type1 = attributes[1]
type2 = attributes[2]
type_counter[type1] = type_counter.get(type1, 0) + 1
type_counter[type2] = type_counter.get(type2, 0) + 1
# type_counter will now be a dictionary with the counts.

Nested dictionaries in Python: how to make them and how to use them?

I'm still trying to figure it out how nested dictionaries in python really works.
I know that when you're using [] it's a list, () it's a tuple and {} a dict.
But when you want to make a nested dictionaries like this structure (that's what a i want) :
{KeyA :
{ValueA :
[KeyB : ValueB],
[Keyc : ValueC],
[KeyD : ValueD]},
{ValueA for each ValueD]}}
For now I have a dict like:
{KeyA : {KeyB : [ValueB],
KeyC : [ValueC],
KeyD : [ValueD]}}
Here's my code:
json_file = importation()
dict_guy = {}
for key, value in json_file['clients'].items():
n_customerID = normalization(value['shortname'])
if n_customerID not in dict_guy:
dict_guy[n_customerID] = {
'clientsName':[],
'company':[],
'contacts':[], }
dict_guy[n_customerID]['clientsName'].append(n_customerID)
dict_guy[n_customerID]['company'].append(normalization(value['name']))
dict_guy[n_customerID]['contacts'].extend([norma_email(item) for item in v\
alue['contacts']])
Can someone please, give me more informations or really explain to me how a nested dict works?
So, I hope I get it right from our conversation in the comments :)
json_file = importation()
dict_guy = {}
for key, value in json_file['clients'].items():
n_customerID = normalization(value['shortname'])
if n_customerID not in dict_guy:
dict_guy[n_customerID] = {
'clientsName':[],
'company':[],
'contacts':{}, } # Assign empty dict, not list
dict_guy[n_customerID]['clientsName'].append(n_customerID)
dict_guy[n_customerID]['company'].append(normalization(value['name']))
for item in value['contacts']:
normalized_email = norma_email(item)
# Use the contacts dictionary like every other dictionary
dict_guy[n_customerID]['contacts'][normalized_email] = n_customerID
There is no problem to simply assign a dictionary to a key inside another dictionary. That's what I do in this code sample. You can create dictionaries nested as deep as you wish.
How that this helped you. If not, we'll work on it further :)
EDIT:
About list/dict comprehensions. You are almost right that:
I know that when you're using [] it's a list, () it's a tuple and {} a dict.
The {} brackets are a little tricky in Python 3. They can be used to create a dictionary as well as a set!
a = {} # a becomes an empty dictionary
a = set() # a becomes an empty set
a = {1,2,3} # a becomes a set with 3 values
a = {1: 1, 2: 4, 3: 9} # a becomes a dictionary with 3 keys
a = {x for x in range(10)} # a becomes a set with 10 elements
a = {x: x*x for x in range(10)} # a becomes a dictionary with 10 keys
Your line dict_guy[n_customerID] = { {'clientsName':[], 'company':[], 'contacts':[]}} tried to create a set with a single dictionary in it and because dictionaries are not hashable, you got the TypeError exception informing you that something is not hashable :) (sets can store only ements that are hashable)
Check out this page.
example = {'app_url': '', 'models': [{'perms': {'add': True, 'change': True,
'delete': True}, 'add_url': '/admin/cms/news/add/', 'admin_url': '/admin/cms/news/',
'name': ''}], 'has_module_perms': True, 'name': u'CMS'}

Resources