Cara menggunakan dictionary contains list python

Contents

Table of Contents

  • Create a List of Dictionaries in Python
  • Access key:value pairs in List of Dictionaries
  • Update key:value pairs of a Dictionary in List of Dictionaries
  • Append a Dictionary to List of Dictionaries
  • Related Tutorials
  • Dict Hash Table
  • Dict Formatting
  • Files Unicode
  • Exercise Incremental Development
  • Exercise: wordcount.py
  • Can we store dictionary in a list?
  • How do I save a dictionary key to a list?
  • How do you store a dictionary in Python?

  • Introduction
  • Create a List of Dictionaries in Python
  • Access key:value pairs in List of Dictionaries
  • Update key:value pairs of a Dictionary in List of Dictionaries
  • Append a Dictionary to List of Dictionaries
  • Summary

In Python, you can have a List of Dictionaries. You already know that elements of the Python List could be objects of any type.

In this tutorial, we will learn how to create a list of dictionaries, how to access them, how to append a dictionary to list and how to modify them.

Create a List of Dictionaries in Python

In the following program, we create a list of length 3, where all the three elements are of type dict.

Python Program

myList = [
	{
		'foo':12,
		'bar':14
	},
	{
		'moo':52,
		'car':641
	},
	{
		'doo':6,
		'tar':84
	}
]

print(myList)

Run

Output

[{'foo': 12, 'bar': 14}, {'moo': 52, 'car': 641}, {'doo': 6, 'tar': 84}]

Each element of the list is a dictionary.

Access key:value pairs in List of Dictionaries

Dictionary is like any element in a list. Therefore, you can access each dictionary of the list using index.

And we know how to access a specific key:value of the dictionary using key.

In the following program, we shall print some of the values of dictionaries in list using keys.

Python Program

myList = [
	{
		'foo':12,
		'bar':14
	},
	{
		'moo':52,
		'car':641
	},
	{
		'doo':6,
		'tar':84
	}
]

print(myList[0])
print(myList[0]['bar'])

print(myList[1])
print(myList[1]['moo'])

print(myList[2])
print(myList[2]['doo'])

Run

Output

{'foo': 12, 'bar': 14}
14
{'moo': 52, 'car': 641}
52
{'doo': 6, 'tar': 84}
6

Update key:value pairs of a Dictionary in List of Dictionaries

In the following program, we shall update some of the key:value pairs of dictionaries in list: Update value for a key in the first dictionary, add a key:value pair to the second dictionary, delete a key:value pair from the third dictionary.

Python Program

myList = [
	{
		'foo':12,
		'bar':14
	},
	{
		'moo':52,
		'car':641
	},
	{
		'doo':6,
		'tar':84
	}
]

#update value for 'bar' in first dictionary
myList[0]['bar'] = 52

#add a new key:value pair to second dictionary
myList[1]['gar'] = 38

#delete a key:value pair from third dictionary
del myList[2]['doo']

print(myList)

Run

Output

[{'foo': 12, 'bar': 52}, {'moo': 52, 'car': 641, 'gar': 38}, {'tar': 84}]

Append a Dictionary to List of Dictionaries

In the following program, we shall append a dictionary to the list of dictionaries.

Python Program

myList = [
	{
		'foo':12,
		'bar':14
	},
	{
		'moo':52,
		'car':641
	},
	{
		'doo':6,
		'tar':84
	}
]

#append dictionary to list
myList.append({'joo':48, 'par':28})

print(myList)

Run

Output

[{'foo': 12, 'bar': 14}, {'moo': 52, 'car': 641}, {'doo': 6, 'tar': 84}, {'joo': 48, 'par': 28}]

Summary

In this tutorial of Python Examples, we learned about list of dictionaries in Python and different operations on the elements of it, with the help of well detailed examples.

  • How to Sort Python List?
  • How to Append List to Another List in Python? – list.extend(list)
  • Python Program to Find Smallest Number in List
  • How to Get List of all Files in Directory and Sub-directories?
  • How to Reverse Python List?
  • Python – Check if List Contains all Elements of Another List
  • How to Insert Item at Specific Index in Python List?
  • Python – List of Strings
  • Python Program to Find Largest Number in a List
  • Python List without Last Element

Dict Hash Table

Python's efficient key/value hash table structure is called a "dict". The contents of a dict can be written as a series of key:value pairs within braces { }, e.g. dict = {key1:value1, key2:value2, ... }. The "empty dict" is just an empty pair of curly braces {}.

Looking up or setting a value in a dict uses square brackets, e.g. dict['foo'] looks up the value under the key 'foo'. Strings, numbers, and tuples work as keys, and any type can be a value. Other types may or may not work correctly as keys (strings and tuples work cleanly since they are immutable). Looking up a value which is not in the dict throws a KeyError -- use "in" to check if the key is in the dict, or use dict.get(key) which returns the value or None if the key is not present (or get(key, not-found) allows you to specify what value to return in the not-found case).

  ## Can build up a dict by starting with the the empty dict {}
  ## and storing key/value pairs into the dict like this:
  ## dict[key] = value-for-that-key
  dict = {}
  dict['a'] = 'alpha'
  dict['g'] = 'gamma'
  dict['o'] = 'omega'

  print(dict) ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}

  print(dict['a'])     ## Simple lookup, returns 'alpha'
  dict['a'] = 6       ## Put new key/value into dict
  'a' in dict         ## True
  ## print(dict['z'])                  ## Throws KeyError
  if 'z' in dict: print(dict['z'])     ## Avoid KeyError
  print(dict.get('z'))  ## None (instead of KeyError)

Cara menggunakan dictionary contains list python

A for loop on a dictionary iterates over its keys by default. The keys will appear in an arbitrary order. The methods dict.keys() and dict.values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary. All of these lists can be passed to the sorted() function.

  ## By default, iterating over a dict iterates over its keys.
  ## Note that the keys are in a random order.
  for key in dict: print(key)
  ## prints a g o
  
  ## Exactly the same as above
  for key in dict.keys(): print(key)

  ## Get the .keys() list:
  print(dict.keys())  ## dict_keys(['a', 'o', 'g'])

  ## Likewise, there's a .values() list of values
  print(dict.values())  ## dict_values(['alpha', 'omega', 'gamma'])

  ## Common case -- loop over the keys in sorted order,
  ## accessing each key/value
  for key in sorted(dict.keys()):
    print(key, dict[key])
  
  ## .items() is the dict expressed as (key, value) tuples
  print(dict.items())  ##  dict_items([('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')])

  ## This loop syntax accesses the whole dict by looping
  ## over the .items() tuple list, accessing one (key, value)
  ## pair on each iteration.
  for k, v in dict.items(): print(k, '>', v)
  ## a > alpha    o > omega     g > gamma

Strategy note: from a performance point of view, the dictionary is one of your greatest tools, and you should use it where you can as an easy way to organize data. For example, you might read a log file where each line begins with an IP address, and store the data into a dict using the IP address as the key, and the list of lines where it appears as the value. Once you've read in the whole file, you can look up any IP address and instantly see its list of lines. The dictionary takes in scattered data and makes it into something coherent.

Dict Formatting

The % operator works conveniently to substitute values from a dict into a string by name:

  h = {}
  h['word'] = 'garfield'
  h['count'] = 42
  s = 'I want %(count)d copies of %(word)s' % h  # %d for int, %s for string
  # 'I want 42 copies of garfield'

  # You can also use str.format().
  s = 'I want {count:d} copies of {word}'.format(h)

Del

The "del" operator does deletions. In the simplest case, it can remove the definition of a variable, as if that variable had not been defined. Del can also be used on list elements or slices to delete that part of the list and to delete entries from a dictionary.

  var = 6
  del var  # var no more!
  
  list = ['a', 'b', 'c', 'd']
  del list[0]     ## Delete first element
  del list[-2:]   ## Delete last two elements
  print(list)      ## ['b']

  dict = {'a':1, 'b':2, 'c':3}
  del dict['b']   ## Delete 'b' entry
  print(dict)      ## {'a':1, 'c':3}

Files

The open() function opens and returns a file handle that can be used to read or write a file in the usual way. The code f = open('name', 'r') opens the file into the variable f, ready for reading operations, and use f.close() when finished. Instead of 'r', use 'w' for writing, and 'a' for append. The standard for-loop works for text files, iterating through the lines of the file (this works only for text files, not binary files). The for-loop technique is a simple and efficient way to look at all the lines in a text file:

  # Echo the contents of a text file
  f = open('foo.txt', 'rt', encoding='utf-8')
  for line in f:   ## iterates over the lines of the file
    print(line, end='')    ## end='' so print does not add an end-of-line char
                           ## since 'line' already includes the end-of-line.
  f.close()

Reading one line at a time has the nice quality that not all the file needs to fit in memory at one time -- handy if you want to look at every line in a 10 gigabyte file without using 10 gigabytes of memory. The f.readlines() method reads the whole file into memory and returns its contents as a list of its lines. The f.read() method reads the whole file into a single string, which can be a handy way to deal with the text all at once, such as with regular expressions we'll see later.

For writing, f.write(string) method is the easiest way to write data to an open output file. Or you can use "print" with an open file like "print(string, file=f)".

Files Unicode

To read and write unicode encoded files use a `'t'` mode and explicitly specify an encoding:

with open('foo.txt', 'rt', encoding='utf-8') as f:
  for line in f:
    # here line is a *unicode* string
  
with open('write_test', encoding='utf-8', mode='wt') as f:
    f.write('\u20ACunicode\u20AC\n') #  €unicode€
    # AKA print('\u20ACunicode\u20AC', file=f)  ## which auto-adds end='\n'

Exercise Incremental Development

Building a Python program, don't write the whole thing in one step. Instead identify just a first milestone, e.g. "well the first step is to extract the list of words." Write the code to get to that milestone, and just print your data structures at that point, and then you can do a sys.exit(0) so the program does not run ahead into its not-done parts. Once the milestone code is working, you can work on code for the next milestone. Being able to look at the printout of your variables at one state can help you think about how you need to transform those variables to get to the next state. Python is very quick with this pattern, allowing you to make a little change and run the program to see how it works. Take advantage of that quick turnaround to build your program in little steps.

Exercise: wordcount.py

Combining all the basic Python material -- strings, lists, dicts, tuples, files -- try the summary wordcount.py exercise in the Basic Exercises.

Can we store dictionary in a list?

Note that the restriction with keys in Python dictionary is only immutable data types can be used as keys, which means we cannot use a dictionary of list as a key . But the same can be done very wisely with values in dictionary. Let's see all the different ways we can create a dictionary of Lists.

How do I save a dictionary key to a list?

To convert Python Dictionary keys to List, you can use dict. keys() method which returns a dict_keys object. This object can be iterated, and if you pass it to list() constructor, it returns a list object with dictionary keys as elements.

How do you store a dictionary in Python?

The most basic way to save dictionaries in Python would be to store them as strings in text files..

Opening a file in write/append text mode..

Converting the dictionary into a string..

Entering the converted string into the file using write function..