Featured

    Featured Posts

Dictionary

 

Different Ways to Creating a dictionary in Python

ü    Dictionary consists of key-value pairs. It is enclosed by curly braces {}.


ü    A dictionary can be created by enclosing item, separated by commas, in curly braces {} Where item is nothing item is a key-value pair and the key and the value is separated by a colon (:). This pair is known as item. Items are separated from each other by a comma (,).

 

ü    keys must be of an immutable data type such as strings, numbers, or tuples.

 

§  We can create empty dictionary object as follows.

d={}

print(d)

print(type(d))

# The Output Will be

{}

<class 'dict'>

We can create dictionary object with some element If we know data in        

advance   as follows





d={"name":"john","age":20,"country":"India"}

print(d)

print(type(d))

# The Output Will be

{'name': 'john', 'age': 20, 'country': 'India'}

<class 'dict'>


§  We can create dictionary object with dynamic some element as follows.

d=eval(input("Enter dictionary :"))  

print(d) 

print(type(d)) 

 

# The Output Will be

Enter Dictionary:{101:'sachin',102:'Vijay',103:'Ajay'}

{101: 'sachin', 102: 'Vijay', 103: 'Ajay'}

<class 'dict'>

 

§  We can create dictionary object using built-in class: dict()  as follows.

 

§  The dict() constructor can be used to create dictionaries from keyword arguments, or from a single iterable of key-value pairs, or from a single dictionary and keyword arguments

d = dict()     

print(d) 

print(type(d)) 

# The Output Will be

{}

<class 'dict'>

 

d = dict(a=1, b=2, c=3)  

print(d)

Output:

{'a': 1, 'b': 2, 'c': 3}

d=dict([('a', 1), ('b', 2), ('c', 3)])  

print(d)

Output:

{'a': 1, 'b': 2, 'c': 3}

 

d=dict({'a' : 1, 'b' : 2}, c=3)

print(d)

Output:

{'a': 1, 'b': 2, 'c': 3}

 

§  We can create dictionary object using Python Dictionary fromKeys() inbuilt function as follows.

 

§  Python Dictionary fromKeys() is an inbuilt function that creates a new dictionary from the given sequence of elements .

dictionary.fromkeys(keys, value)

§  This Method takes two parameter first parameter is key that is required parameter.and it is an iterable specifying the keys of the new dictionary.

 

 

§  The Second parameter is value parameter that is optional and the value for all keys. The default value is None.

 

§  Python fromkeys() method returns a new dictionary with a given sequence of elements as the keys of the dictionary.

employees = ['Scott', 'Mark', 'John']

defaults = {'Application Developer', 1000}

 

resDict = dict.fromkeys(employees, defaults)

print(resDict)

Output:

{

'Scott': {1000, 'Application Developer'}, '

Mark': {1000, 'Application Developer'}, '

John': {1000, 'Application Developer'}



How to access Element from the dictionary

§  The elements of a dictionary can be accessed via a key.

d= {101: 'sachin', 102: 'Vijay', 103: 'Ajay'}

print(d[101])#The OutPut:sachin

print(d[102])#The OutPut:Vijay

print(d[103])#The OutPut:Ajay

    If the specified key is not available then we will get KeyError.

print(d[104])

KeyError: 104

 

How We can Avoid KeyError Exceptions

 

§  One common pitfall when using dictionaries is to access a non-existent key. This typically results in a KeyError exception.

 

§  One way to avoid key errors is to use the dict.get method, which allows you to specify a default value to return in the case of an absent key.

                    value = mydict.get(key, default_value)

§  Which returns mydict[key] if it exists, but otherwise returns default_value. Note that this doesn't add key to mydict.

 

d={101: 'sachin', 102: 'Vijay', 103: 'Ajay'}

print(d[101])#The OutPut:sachin

print(d[102])#The OutPut:Vijay

print(d[103])#The OutPut:Ajay

print(d.get(104,'Hello'))#The OutPut:Hello

 

§  In the given example 104 key is not exist if we try to fetch element by using 104 key then we get default value hello because 104 is not key of this given dict. this doesn't add key to dict.

 

§  if you want to retain that key value pair, you should use mydict.setdefault(key, default_value), which does store the key value pair.

 

d={101: 'sachin', 102: 'Vijay', 103: 'Ajay'}

print(d[101])#The OutPut:sachin

print(d[102])#The OutPut:Vijay

print(d[103])#The OutPut:Ajay

print(d.setdefault(104,'Hello'))#The OutPut:Hello

print(d)

Output:

sachin

Vijay

Ajay

Hello

{101: 'sachin', 102: 'Vijay', 103: 'Ajay', 104: 'Hello'}

 

 

§  An alternative way to deal with the problem.

§  You could also check if the key is in the dictionary.

if key in mydict:

    value = mydict[key]

else:

    value = default_value

 

 

 

 

How to Check that given key or given value exists in a dictionary or not

# Create first dictionary

d1={'a':1,'b':2,'c':3}

#Check given key exists in a dictionary

print('a' in d1)#The Output:True

#Another Way Check given key exists in a dictionary

print('a' in d1.keys())#The Output:True

#Check given Value exists in a dictionary

print(2 in d1.values())#The Output:True

 

 

Iterating over a Dictionary

§  You can iterate over the dictionary elements using for loop like below:

for element in dictionary:

       do operation

d = {'a': 1, 'b': 2, 'c':3}

for key in d:

print(key, d[key])

Output:

a 1

b 2

         c 3

 
















Sidenav | Angular Material

 

 dsdffg

§  In this tutorial we will learn Sidenav | Angular Material UI components. 

§  The sidenav components are designed to add side content to a fullscreen app. 

§  to setup a sidenav we use three components the first one is mat-sidenav-container which access a container to the sidenav as well as the main content within the container we have <mat-sidenav> which represents the site content and then we have mat-sidenav-content which represents the main content it is important that the site content and the main content are placed within the container.

If you don't want some elements to be affected by this container for example header and footer you can place them outside the mat-sidenav-container

<mat-sidenav-container>
<mat-sidenav>SideNav</mat-sidenav>
<mat-sidenav-content>Main content</mat-sidenav-content>
</mat-sidenav-container>

§  Save the file and run the application and check the browser the output is not quite what we expect we can see the main content to the side now is not seen.


  §  Actually this is the expected behavior mat-sidenav is always hidden by default. There are couples of ways to open or show the side-nav. the simplest way is to add the opened attribute on the mat-sidenav component.

<mat-sidenav-container>
<mat-sidenav opened>SideNav</mat-sidenav>
<mat-sidenav-content>Main content</mat-sidenav-content>
</mat-sidenav-container>



§  Save the file and check the browser you should be able to see the side-nav as well but UI is not clear so let me add some basic styling . now open app.component.css file

mat-sidenav-container{
height: 100%;
}
mat-sidenav,mat-sidenav-content{
padding: 16px;
}
mat-sidenav{
background-color: lightcoral;
width: 200px;
}


Save  the file and run the application and check the browser.It is much more clear the side-nav appears like an overlay on the main-content and when I click outside the side-nav it closes and we can see the main content now once we close it there there is no way to open it again so rather than setting the opened attribute like here let's bind it to a property which we can then control using a button we will be using two way binding to the first step is to import the formsModule in app.module.ts



import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FlexLayoutModule } from '@angular/flex-layout';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { NavBarComponent } from './nav-bar/nav-bar.component';
import {ReactiveFormsModule} from '@angular/forms';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import {MatButtonModule} from '@angular/material/button';
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatCardModule} from '@angular/material/card';
import {MatSidenavModule} from '@angular/material/sidenav';
import {FormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
LoginComponent,
RegisterComponent,
NavBarComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
ReactiveFormsModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
MatToolbarModule,
MatCardModule,
MatSidenavModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

§  let's we are using two way Binding in app.component.ts which is the component class i am going to  create a new property called opened and set it to false in the HTML bind the opened attribute to the opened property and create a button that will toggle the open the property value.



§  Save the files and click the browser the side-nav should be initially hidden because we have initialised to false I click on the button and the side navigation shown and click outside the side-nav and it automatically hides this is the first method to show or hide the side-nav.


§  The best is the first method to show or hide the site now before we take a look at the next method I want to quickly show you the different modes that can be applied to a side-nav the mode for a side-nav can be specified using the mode attribute on the mat-sidenav component the default mode is over .


<mat-sidenav-container>
<mat-sidenav mode="over" [(opened)]="opened">SideNav</mat-sidenav>
<mat-sidenav-content>Main content
<button (click)="opened=!opened">Toggle</button>
</mat-sidenav-content>
</mat-sidenav-container>



§  This is the mode we have seen so far we go back to the browser you can see that there is no change from what we have already seen the side-nav floats over the main content which is covered by a backdrop

§  the second possible value for the mode attribute is push Centre change over to push at the of this works in the browser I click on the button the side-nav  appears with this time the side that pushes the primary content that of its way covering it with a backdrop.


<mat-sidenav-container>
<mat-sidenav mode="push" [(opened)]="opened">SideNav</mat-sidenav>
<mat-sidenav-content>Main content
<button (click)="opened=!opened">Toggle</button>
</mat-sidenav-content>
</mat-sidenav-container>

§  The final possible mode is side the mode is equal to side in this mode the side-nav appears side by side with the main content shrinking the main content width to make space for the side-nav.


<mat-sidenav-container>
<mat-sidenav mode="side" [(opened)]="opened">SideNav</mat-sidenav>
<mat-sidenav-content>Main content
<button (click)="opened=!opened">Toggle</button>
</mat-sidenav-content>
</mat-sidenav-container>

§  There are three possible modes are over push and side.

§  The second way to open or close the side now is by invoking the open or closed method on the side-nav itself for this method I will create a template reference variable on the mat-sidenav component and now I can create two buttons that will call the open and close method on this template reference variable .



§  Save the file and go back to the browser I click on open and the side-nav opens I click on close and the side-nav closes to this is the second method.

 §  Third Method is to simply toggle the side-nav I calling the toggle method this is also the approach you might want to take when you have a hamburger icon for example I will create another button in the main content the text is going to be toggle on click of this button I simply call the toggle method on the sidenav reference variable .


<mat-sidenav-container>
<mat-sidenav #sidenav mode="side" [(opened)]="opened">SideNav</mat-sidenav>
<mat-sidenav-content>Main content
<button (click)="opened=!opened">Toggle</button>
<button (click)="sidenav.open()">Open</button>
<button (click)="sidenav.close()">Close</button>
<button (click)="sidenav.toggle()">Toggle</button>
</mat-sidenav-content>
</mat-sidenav-container>



§  Save the and go to the browser and click on the toggle button it opens I click again it closes so these are the three methods.

§  if  you want to perform some action on open or close of the side-nav you can listen to the opened and closed events back in vs code in app.component.ts files I am going to create method called log which accept a parameter called state and simply log that to the console now in HTML we can listen to opened and closed event and call a log method passing the appropriate value so on mat-sidenav listen to open event and call the log method passing  the string opened similarly on the closed event call the method passing in the string closest


<mat-sidenav-container>
<mat-sidenav #sidenav mode="side" (opened)="log('Opened')" (closed)="log('Closed')" [(opened)]="opened">SideNav</mat-sidenav>
<mat-sidenav-content>Main content
<button (click)="opened=!opened">Toggle</button>
<button (click)="sidenav.open()">Open</button>
<button (click)="sidenav.close()">Close</button>
<button (click)="sidenav.toggle()">Toggle</button>
</mat-sidenav-content>
</mat-sidenav-container>


import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'LoginRegisterReactiveProject';
opened=false;
log(state){
console.log(state);
}
}















www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews