JavaPython:Sõnastikud

Allikas: Kursused
Redaktsioon seisuga 2. veebruar 2016, kell 11:01 kasutajalt Triin (arutelu | kaastöö)
Mine navigeerimisribale Mine otsikasti
Java vs Python

Pythoni sõnastikud on sarnased Java "map"-idele.

A HashMap is like a Python dictionary, but uses only object syntax. There are no literals. Declaration and creation look like:

HashMap<keyType, valueType> variable = new HashSet<keyType, valueType>();

Some methods:

type put(key, value) (returns previous value), type get(key), boolean containsKey(key).

Näide

Java Python
<syntaxhighlight lang="java" line="1" >

HashMap<String, String> phoneBook =

                       new HashMap<String, String>();

phoneBook.put("Mike", "555-1111"); phoneBook.put("Lucy", "555-2222"); phoneBook.put("Jack", "555-3333");

//iterate over HashMap Map<String, String> map = new HashMap<String, String>(); for (Map.Entry<String, String> entry : map.entrySet()) {

   System.out.println("Key = " + entry.getKey() +
     ", Value = " + entry.getValue());

}

//get key value phoneBook.get("Mike");

//get all key Set keys = phoneBook.keySet();

//get number of elements phoneBook.size();

//delete all elements phoneBook.clear();

//delete an element phoneBook.remove("Lucy"); </syntaxhighlight>

<syntaxhighlight lang="python" line="2" >
  1. create an empty dictionary

phoneBook = {} phoneBook = {"Mike":"555-1111",

            "Lucy":"555-2222", 
            "Jack":"555-3333"}

  1. iterate over dictionary

for key in phoneBook:

   print(key, phoneBook[key])

  1. add an element

phoneBook["Mary"] = "555-6666"

  1. delete an element

del phoneBook["Mike"]

  1. get number of elements

count = len(phoneBook)

  1. can have different types

phoneBook["Susan"] = (1,2,3,4)

  1. return all keys

print phoneBook.keys()

  1. delete all the elements

phoneBook.clear() </syntaxhighlight>