We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Count constructor crashes when data is empty
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: 0.15.1
- **Python version**: 3.7.3
- **Operating system**: Mac OS Catalina 10.15.6

### What is the current behavior?
I simply ran a circuit which does not perform any measurements. On the returned results, `get_counts()` crashes because an empty dictionary is passed into the `Count` constructor and the constructor tries to iterate on the empty dictionary.

I tried this on an older version, Terra 0.14.2, which instead of `Count` uses `postprocess.format_counts()`, which simply ignores the empty dictionary and returns an empty dictionary in this case. This did not crash.


### Steps to reproduce the problem
Run any circuit without calling `measure()`, then try to apply `get_counts()` to the results.


### What is the expected behavior?
`get_counts()` should return an empty dictionary (and not crash).


### Suggested solutions
A simple check for an empty dictionary in the `Count` constructor would be sufficient, I think.



--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `qiskit/result/counts.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 # This code is part of Qiskit.
4 #
5 # (C) Copyright IBM 2020.
6 #
7 # This code is licensed under the Apache License, Version 2.0. You may
8 # obtain a copy of this license in the LICENSE.txt file in the root directory
9 # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
10 #
11 # Any modifications or derivative works of this code must retain this
12 # copyright notice, and modified files need to carry a notice indicating
13 # that they have been altered from the originals.
14 
15 """A container class for counts from a circuit execution."""
16 
17 import re
18 
19 from qiskit.result import postprocess
20 from qiskit import exceptions
21 
22 
23 # NOTE: A dict subclass should not overload any dunder methods like __getitem__
24 # this can cause unexpected behavior and issues as the cPython dict
25 # implementation has many standard methods in C for performance and the dunder
26 # methods are not always used as expected. For example, update() doesn't call
27 # __setitem__ so overloading __setitem__ would not always provide the expected
28 # result
29 class Counts(dict):
30     """A class to store a counts result from a circuit execution."""
31 
32     def __init__(self, data, time_taken=None, creg_sizes=None,
33                  memory_slots=None):
34         """Build a counts object
35 
36         Args:
37             data (dict): The dictionary input for the counts. Where the keys
38                 represent a measured classical value and the value is an
39                 integer the number of shots with that result.
40                 The keys can be one of several formats:
41 
42                      * A hexademical string of the form ``"0x4a"``
43                      * A bit string prefixed with ``0b`` for example ``'0b1011'``
44                      * A bit string formatted across register and memory slots.
45                        For example, ``'00 10'``.
46                      * A dit string, for example ``'02'``. Note for objects created
47                        with dit strings the ``creg_sizes``and ``memory_slots``
48                        kwargs don't work and :meth:`hex_outcomes` and
49                        :meth:`int_outcomes` also do not work.
50 
51             time_taken (float): The duration of the experiment that generated
52                 the counts
53             creg_sizes (list): a nested list where the inner element is a list
54                 of tuples containing both the classical register name and
55                 classical register size. For example,
56                 ``[('c_reg', 2), ('my_creg', 4)]``.
57             memory_slots (int): The number of total ``memory_slots`` in the
58                 experiment.
59         Raises:
60             TypeError: If the input key type is not an int or string
61             QiskitError: If a dit string key is input with creg_sizes and/or
62                 memory_slots
63         """
64         bin_data = None
65         data = dict(data)
66         first_key = next(iter(data.keys()))
67         if isinstance(first_key, int):
68             self.int_raw = data
69             self.hex_raw = {
70                 hex(key): value for key, value in self.int_raw.items()}
71         elif isinstance(first_key, str):
72             if first_key.startswith('0x'):
73                 self.hex_raw = data
74                 self.int_raw = {
75                     int(key, 0): value for key, value in self.hex_raw.items()}
76             elif first_key.startswith('0b'):
77                 self.int_raw = {
78                     int(key, 0): value for key, value in data.items()}
79                 self.hex_raw = {
80                     hex(key): value for key, value in self.int_raw.items()}
81             else:
82                 if not creg_sizes and not memory_slots:
83                     self.hex_raw = None
84                     self.int_raw = None
85                     bin_data = data
86                 else:
87                     bitstring_regex = re.compile(r'^[01\s]+$')
88                     hex_dict = {}
89                     int_dict = {}
90                     for bitstring, value in data.items():
91                         if not bitstring_regex.search(bitstring):
92                             raise exceptions.QiskitError(
93                                 'Counts objects with dit strings do not '
94                                 'currently support dit string formatting parameters '
95                                 'creg_sizes or memory_slots')
96                         int_key = int(bitstring.replace(" ", ""), 2)
97                         int_dict[int_key] = value
98                         hex_dict[hex(int_key)] = value
99                     self.hex_raw = hex_dict
100                     self.int_raw = int_dict
101         else:
102             raise TypeError("Invalid input key type %s, must be either an int "
103                             "key or string key with hexademical value or bit string")
104         header = {}
105         self.creg_sizes = creg_sizes
106         if self.creg_sizes:
107             header['creg_sizes'] = self.creg_sizes
108         self.memory_slots = memory_slots
109         if self.memory_slots:
110             header['memory_slots'] = self.memory_slots
111         if not bin_data:
112             bin_data = postprocess.format_counts(self.hex_raw, header=header)
113         super().__init__(bin_data)
114         self.time_taken = time_taken
115 
116     def most_frequent(self):
117         """Return the most frequent count
118 
119         Returns:
120             str: The bit string for the most frequent result
121         Raises:
122             QiskitError: when there is >1 count with the same max counts
123         """
124         max_value = max(self.values())
125         max_values_counts = [x[0] for x in self.items() if x[1] == max_value]
126         if len(max_values_counts) != 1:
127             raise exceptions.QiskitError(
128                 "Multiple values have the same maximum counts: %s" %
129                 ','.join(max_values_counts))
130         return max_values_counts[0]
131 
132     def hex_outcomes(self):
133         """Return a counts dictionary with hexademical string keys
134 
135         Returns:
136             dict: A dictionary with the keys as hexadecimal strings instead of
137                 bitstrings
138         Raises:
139             QiskitError: If the Counts object contains counts for dit strings
140         """
141         if self.hex_raw:
142             return {key.lower(): value for key, value in self.hex_raw.items()}
143         else:
144             bitstring_regex = re.compile(r'^[01\s]+$')
145             out_dict = {}
146             for bitstring, value in self.items():
147                 if not bitstring_regex.search(bitstring):
148                     raise exceptions.QiskitError(
149                         'Counts objects with dit strings do not '
150                         'currently support conversion to hexadecimal')
151                 int_key = int(bitstring.replace(" ", ""), 2)
152                 out_dict[hex(int_key)] = value
153             return out_dict
154 
155     def int_outcomes(self):
156         """Build a counts dictionary with integer keys instead of count strings
157 
158         Returns:
159             dict: A dictionary with the keys as integers instead of bitstrings
160         Raises:
161             QiskitError: If the Counts object contains counts for dit strings
162         """
163         if self.int_raw:
164             return self.int_raw
165         else:
166             bitstring_regex = re.compile(r'^[01\s]+$')
167             out_dict = {}
168             for bitstring, value in self.items():
169                 if not bitstring_regex.search(bitstring):
170                     raise exceptions.QiskitError(
171                         'Counts objects with dit strings do not '
172                         'currently support conversion to integer')
173                 int_key = int(bitstring.replace(" ", ""), 2)
174                 out_dict[int_key] = value
175             return out_dict
176
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/qiskit/result/counts.py b/qiskit/result/counts.py
--- a/qiskit/result/counts.py
+++ b/qiskit/result/counts.py
@@ -63,44 +63,49 @@
         """
         bin_data = None
         data = dict(data)
-        first_key = next(iter(data.keys()))
-        if isinstance(first_key, int):
-            self.int_raw = data
-            self.hex_raw = {
-                hex(key): value for key, value in self.int_raw.items()}
-        elif isinstance(first_key, str):
-            if first_key.startswith('0x'):
-                self.hex_raw = data
-                self.int_raw = {
-                    int(key, 0): value for key, value in self.hex_raw.items()}
-            elif first_key.startswith('0b'):
-                self.int_raw = {
-                    int(key, 0): value for key, value in data.items()}
+        if not data:
+            self.int_raw = {}
+            self.hex_raw = {}
+            bin_data = {}
+        else:
+            first_key = next(iter(data.keys()))
+            if isinstance(first_key, int):
+                self.int_raw = data
                 self.hex_raw = {
                     hex(key): value for key, value in self.int_raw.items()}
-            else:
-                if not creg_sizes and not memory_slots:
-                    self.hex_raw = None
-                    self.int_raw = None
-                    bin_data = data
+            elif isinstance(first_key, str):
+                if first_key.startswith('0x'):
+                    self.hex_raw = data
+                    self.int_raw = {
+                        int(key, 0): value for key, value in self.hex_raw.items()}
+                elif first_key.startswith('0b'):
+                    self.int_raw = {
+                        int(key, 0): value for key, value in data.items()}
+                    self.hex_raw = {
+                        hex(key): value for key, value in self.int_raw.items()}
                 else:
-                    bitstring_regex = re.compile(r'^[01\s]+$')
-                    hex_dict = {}
-                    int_dict = {}
-                    for bitstring, value in data.items():
-                        if not bitstring_regex.search(bitstring):
-                            raise exceptions.QiskitError(
-                                'Counts objects with dit strings do not '
-                                'currently support dit string formatting parameters '
-                                'creg_sizes or memory_slots')
-                        int_key = int(bitstring.replace(" ", ""), 2)
-                        int_dict[int_key] = value
-                        hex_dict[hex(int_key)] = value
-                    self.hex_raw = hex_dict
-                    self.int_raw = int_dict
-        else:
-            raise TypeError("Invalid input key type %s, must be either an int "
-                            "key or string key with hexademical value or bit string")
+                    if not creg_sizes and not memory_slots:
+                        self.hex_raw = None
+                        self.int_raw = None
+                        bin_data = data
+                    else:
+                        bitstring_regex = re.compile(r'^[01\s]+$')
+                        hex_dict = {}
+                        int_dict = {}
+                        for bitstring, value in data.items():
+                            if not bitstring_regex.search(bitstring):
+                                raise exceptions.QiskitError(
+                                    'Counts objects with dit strings do not '
+                                    'currently support dit string formatting parameters '
+                                    'creg_sizes or memory_slots')
+                            int_key = int(bitstring.replace(" ", ""), 2)
+                            int_dict[int_key] = value
+                            hex_dict[hex(int_key)] = value
+                        self.hex_raw = hex_dict
+                        self.int_raw = int_dict
+            else:
+                raise TypeError("Invalid input key type %s, must be either an int "
+                                "key or string key with hexademical value or bit string")
         header = {}
         self.creg_sizes = creg_sizes
         if self.creg_sizes:
@@ -119,8 +124,12 @@
         Returns:
             str: The bit string for the most frequent result
         Raises:
-            QiskitError: when there is >1 count with the same max counts
+            QiskitError: when there is >1 count with the same max counts, or
+                an empty object.
         """
+        if not self:
+            raise exceptions.QiskitError(
+                "Can not return a most frequent count on an empty object")
         max_value = max(self.values())
         max_values_counts = [x[0] for x in self.items() if x[1] == max_value]
         if len(max_values_counts) != 1:

{"golden_diff": "diff --git a/qiskit/result/counts.py b/qiskit/result/counts.py\n--- a/qiskit/result/counts.py\n+++ b/qiskit/result/counts.py\n@@ -63,44 +63,49 @@\n         \"\"\"\n         bin_data = None\n         data = dict(data)\n-        first_key = next(iter(data.keys()))\n-        if isinstance(first_key, int):\n-            self.int_raw = data\n-            self.hex_raw = {\n-                hex(key): value for key, value in self.int_raw.items()}\n-        elif isinstance(first_key, str):\n-            if first_key.startswith('0x'):\n-                self.hex_raw = data\n-                self.int_raw = {\n-                    int(key, 0): value for key, value in self.hex_raw.items()}\n-            elif first_key.startswith('0b'):\n-                self.int_raw = {\n-                    int(key, 0): value for key, value in data.items()}\n+        if not data:\n+            self.int_raw = {}\n+            self.hex_raw = {}\n+            bin_data = {}\n+        else:\n+            first_key = next(iter(data.keys()))\n+            if isinstance(first_key, int):\n+                self.int_raw = data\n                 self.hex_raw = {\n                     hex(key): value for key, value in self.int_raw.items()}\n-            else:\n-                if not creg_sizes and not memory_slots:\n-                    self.hex_raw = None\n-                    self.int_raw = None\n-                    bin_data = data\n+            elif isinstance(first_key, str):\n+                if first_key.startswith('0x'):\n+                    self.hex_raw = data\n+                    self.int_raw = {\n+                        int(key, 0): value for key, value in self.hex_raw.items()}\n+                elif first_key.startswith('0b'):\n+                    self.int_raw = {\n+                        int(key, 0): value for key, value in data.items()}\n+                    self.hex_raw = {\n+                        hex(key): value for key, value in self.int_raw.items()}\n                 else:\n-                    bitstring_regex = re.compile(r'^[01\\s]+$')\n-                    hex_dict = {}\n-                    int_dict = {}\n-                    for bitstring, value in data.items():\n-                        if not bitstring_regex.search(bitstring):\n-                            raise exceptions.QiskitError(\n-                                'Counts objects with dit strings do not '\n-                                'currently support dit string formatting parameters '\n-                                'creg_sizes or memory_slots')\n-                        int_key = int(bitstring.replace(\" \", \"\"), 2)\n-                        int_dict[int_key] = value\n-                        hex_dict[hex(int_key)] = value\n-                    self.hex_raw = hex_dict\n-                    self.int_raw = int_dict\n-        else:\n-            raise TypeError(\"Invalid input key type %s, must be either an int \"\n-                            \"key or string key with hexademical value or bit string\")\n+                    if not creg_sizes and not memory_slots:\n+                        self.hex_raw = None\n+                        self.int_raw = None\n+                        bin_data = data\n+                    else:\n+                        bitstring_regex = re.compile(r'^[01\\s]+$')\n+                        hex_dict = {}\n+                        int_dict = {}\n+                        for bitstring, value in data.items():\n+                            if not bitstring_regex.search(bitstring):\n+                                raise exceptions.QiskitError(\n+                                    'Counts objects with dit strings do not '\n+                                    'currently support dit string formatting parameters '\n+                                    'creg_sizes or memory_slots')\n+                            int_key = int(bitstring.replace(\" \", \"\"), 2)\n+                            int_dict[int_key] = value\n+                            hex_dict[hex(int_key)] = value\n+                        self.hex_raw = hex_dict\n+                        self.int_raw = int_dict\n+            else:\n+                raise TypeError(\"Invalid input key type %s, must be either an int \"\n+                                \"key or string key with hexademical value or bit string\")\n         header = {}\n         self.creg_sizes = creg_sizes\n         if self.creg_sizes:\n@@ -119,8 +124,12 @@\n         Returns:\n             str: The bit string for the most frequent result\n         Raises:\n-            QiskitError: when there is >1 count with the same max counts\n+            QiskitError: when there is >1 count with the same max counts, or\n+                an empty object.\n         \"\"\"\n+        if not self:\n+            raise exceptions.QiskitError(\n+                \"Can not return a most frequent count on an empty object\")\n         max_value = max(self.values())\n         max_values_counts = [x[0] for x in self.items() if x[1] == max_value]\n         if len(max_values_counts) != 1:\n", "issue": "Count constructor crashes when data is empty\n<!-- \u26a0\ufe0f If you do not respect this template, your issue will be closed -->\r\n<!-- \u26a0\ufe0f Make sure to browse the opened and closed issues -->\r\n\r\n### Information\r\n\r\n- **Qiskit Terra version**: 0.15.1\r\n- **Python version**: 3.7.3\r\n- **Operating system**: Mac OS Catalina 10.15.6\r\n\r\n### What is the current behavior?\r\nI simply ran a circuit which does not perform any measurements. On the returned results, `get_counts()` crashes because an empty dictionary is passed into the `Count` constructor and the constructor tries to iterate on the empty dictionary.\r\n\r\nI tried this on an older version, Terra 0.14.2, which instead of `Count` uses `postprocess.format_counts()`, which simply ignores the empty dictionary and returns an empty dictionary in this case. This did not crash.\r\n\r\n\r\n### Steps to reproduce the problem\r\nRun any circuit without calling `measure()`, then try to apply `get_counts()` to the results.\r\n\r\n\r\n### What is the expected behavior?\r\n`get_counts()` should return an empty dictionary (and not crash).\r\n\r\n\r\n### Suggested solutions\r\nA simple check for an empty dictionary in the `Count` constructor would be sufficient, I think.\r\n\r\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2020.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"A container class for counts from a circuit execution.\"\"\"\n\nimport re\n\nfrom qiskit.result import postprocess\nfrom qiskit import exceptions\n\n\n# NOTE: A dict subclass should not overload any dunder methods like __getitem__\n# this can cause unexpected behavior and issues as the cPython dict\n# implementation has many standard methods in C for performance and the dunder\n# methods are not always used as expected. For example, update() doesn't call\n# __setitem__ so overloading __setitem__ would not always provide the expected\n# result\nclass Counts(dict):\n    \"\"\"A class to store a counts result from a circuit execution.\"\"\"\n\n    def __init__(self, data, time_taken=None, creg_sizes=None,\n                 memory_slots=None):\n        \"\"\"Build a counts object\n\n        Args:\n            data (dict): The dictionary input for the counts. Where the keys\n                represent a measured classical value and the value is an\n                integer the number of shots with that result.\n                The keys can be one of several formats:\n\n                     * A hexademical string of the form ``\"0x4a\"``\n                     * A bit string prefixed with ``0b`` for example ``'0b1011'``\n                     * A bit string formatted across register and memory slots.\n                       For example, ``'00 10'``.\n                     * A dit string, for example ``'02'``. Note for objects created\n                       with dit strings the ``creg_sizes``and ``memory_slots``\n                       kwargs don't work and :meth:`hex_outcomes` and\n                       :meth:`int_outcomes` also do not work.\n\n            time_taken (float): The duration of the experiment that generated\n                the counts\n            creg_sizes (list): a nested list where the inner element is a list\n                of tuples containing both the classical register name and\n                classical register size. For example,\n                ``[('c_reg', 2), ('my_creg', 4)]``.\n            memory_slots (int): The number of total ``memory_slots`` in the\n                experiment.\n        Raises:\n            TypeError: If the input key type is not an int or string\n            QiskitError: If a dit string key is input with creg_sizes and/or\n                memory_slots\n        \"\"\"\n        bin_data = None\n        data = dict(data)\n        first_key = next(iter(data.keys()))\n        if isinstance(first_key, int):\n            self.int_raw = data\n            self.hex_raw = {\n                hex(key): value for key, value in self.int_raw.items()}\n        elif isinstance(first_key, str):\n            if first_key.startswith('0x'):\n                self.hex_raw = data\n                self.int_raw = {\n                    int(key, 0): value for key, value in self.hex_raw.items()}\n            elif first_key.startswith('0b'):\n                self.int_raw = {\n                    int(key, 0): value for key, value in data.items()}\n                self.hex_raw = {\n                    hex(key): value for key, value in self.int_raw.items()}\n            else:\n                if not creg_sizes and not memory_slots:\n                    self.hex_raw = None\n                    self.int_raw = None\n                    bin_data = data\n                else:\n                    bitstring_regex = re.compile(r'^[01\\s]+$')\n                    hex_dict = {}\n                    int_dict = {}\n                    for bitstring, value in data.items():\n                        if not bitstring_regex.search(bitstring):\n                            raise exceptions.QiskitError(\n                                'Counts objects with dit strings do not '\n                                'currently support dit string formatting parameters '\n                                'creg_sizes or memory_slots')\n                        int_key = int(bitstring.replace(\" \", \"\"), 2)\n                        int_dict[int_key] = value\n                        hex_dict[hex(int_key)] = value\n                    self.hex_raw = hex_dict\n                    self.int_raw = int_dict\n        else:\n            raise TypeError(\"Invalid input key type %s, must be either an int \"\n                            \"key or string key with hexademical value or bit string\")\n        header = {}\n        self.creg_sizes = creg_sizes\n        if self.creg_sizes:\n            header['creg_sizes'] = self.creg_sizes\n        self.memory_slots = memory_slots\n        if self.memory_slots:\n            header['memory_slots'] = self.memory_slots\n        if not bin_data:\n            bin_data = postprocess.format_counts(self.hex_raw, header=header)\n        super().__init__(bin_data)\n        self.time_taken = time_taken\n\n    def most_frequent(self):\n        \"\"\"Return the most frequent count\n\n        Returns:\n            str: The bit string for the most frequent result\n        Raises:\n            QiskitError: when there is >1 count with the same max counts\n        \"\"\"\n        max_value = max(self.values())\n        max_values_counts = [x[0] for x in self.items() if x[1] == max_value]\n        if len(max_values_counts) != 1:\n            raise exceptions.QiskitError(\n                \"Multiple values have the same maximum counts: %s\" %\n                ','.join(max_values_counts))\n        return max_values_counts[0]\n\n    def hex_outcomes(self):\n        \"\"\"Return a counts dictionary with hexademical string keys\n\n        Returns:\n            dict: A dictionary with the keys as hexadecimal strings instead of\n                bitstrings\n        Raises:\n            QiskitError: If the Counts object contains counts for dit strings\n        \"\"\"\n        if self.hex_raw:\n            return {key.lower(): value for key, value in self.hex_raw.items()}\n        else:\n            bitstring_regex = re.compile(r'^[01\\s]+$')\n            out_dict = {}\n            for bitstring, value in self.items():\n                if not bitstring_regex.search(bitstring):\n                    raise exceptions.QiskitError(\n                        'Counts objects with dit strings do not '\n                        'currently support conversion to hexadecimal')\n                int_key = int(bitstring.replace(\" \", \"\"), 2)\n                out_dict[hex(int_key)] = value\n            return out_dict\n\n    def int_outcomes(self):\n        \"\"\"Build a counts dictionary with integer keys instead of count strings\n\n        Returns:\n            dict: A dictionary with the keys as integers instead of bitstrings\n        Raises:\n            QiskitError: If the Counts object contains counts for dit strings\n        \"\"\"\n        if self.int_raw:\n            return self.int_raw\n        else:\n            bitstring_regex = re.compile(r'^[01\\s]+$')\n            out_dict = {}\n            for bitstring, value in self.items():\n                if not bitstring_regex.search(bitstring):\n                    raise exceptions.QiskitError(\n                        'Counts objects with dit strings do not '\n                        'currently support conversion to integer')\n                int_key = int(bitstring.replace(\" \", \"\"), 2)\n                out_dict[int_key] = value\n            return out_dict\n", "path": "qiskit/result/counts.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2020.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"A container class for counts from a circuit execution.\"\"\"\n\nimport re\n\nfrom qiskit.result import postprocess\nfrom qiskit import exceptions\n\n\n# NOTE: A dict subclass should not overload any dunder methods like __getitem__\n# this can cause unexpected behavior and issues as the cPython dict\n# implementation has many standard methods in C for performance and the dunder\n# methods are not always used as expected. For example, update() doesn't call\n# __setitem__ so overloading __setitem__ would not always provide the expected\n# result\nclass Counts(dict):\n    \"\"\"A class to store a counts result from a circuit execution.\"\"\"\n\n    def __init__(self, data, time_taken=None, creg_sizes=None,\n                 memory_slots=None):\n        \"\"\"Build a counts object\n\n        Args:\n            data (dict): The dictionary input for the counts. Where the keys\n                represent a measured classical value and the value is an\n                integer the number of shots with that result.\n                The keys can be one of several formats:\n\n                     * A hexademical string of the form ``\"0x4a\"``\n                     * A bit string prefixed with ``0b`` for example ``'0b1011'``\n                     * A bit string formatted across register and memory slots.\n                       For example, ``'00 10'``.\n                     * A dit string, for example ``'02'``. Note for objects created\n                       with dit strings the ``creg_sizes``and ``memory_slots``\n                       kwargs don't work and :meth:`hex_outcomes` and\n                       :meth:`int_outcomes` also do not work.\n\n            time_taken (float): The duration of the experiment that generated\n                the counts\n            creg_sizes (list): a nested list where the inner element is a list\n                of tuples containing both the classical register name and\n                classical register size. For example,\n                ``[('c_reg', 2), ('my_creg', 4)]``.\n            memory_slots (int): The number of total ``memory_slots`` in the\n                experiment.\n        Raises:\n            TypeError: If the input key type is not an int or string\n            QiskitError: If a dit string key is input with creg_sizes and/or\n                memory_slots\n        \"\"\"\n        bin_data = None\n        data = dict(data)\n        if not data:\n            self.int_raw = {}\n            self.hex_raw = {}\n            bin_data = {}\n        else:\n            first_key = next(iter(data.keys()))\n            if isinstance(first_key, int):\n                self.int_raw = data\n                self.hex_raw = {\n                    hex(key): value for key, value in self.int_raw.items()}\n            elif isinstance(first_key, str):\n                if first_key.startswith('0x'):\n                    self.hex_raw = data\n                    self.int_raw = {\n                        int(key, 0): value for key, value in self.hex_raw.items()}\n                elif first_key.startswith('0b'):\n                    self.int_raw = {\n                        int(key, 0): value for key, value in data.items()}\n                    self.hex_raw = {\n                        hex(key): value for key, value in self.int_raw.items()}\n                else:\n                    if not creg_sizes and not memory_slots:\n                        self.hex_raw = None\n                        self.int_raw = None\n                        bin_data = data\n                    else:\n                        bitstring_regex = re.compile(r'^[01\\s]+$')\n                        hex_dict = {}\n                        int_dict = {}\n                        for bitstring, value in data.items():\n                            if not bitstring_regex.search(bitstring):\n                                raise exceptions.QiskitError(\n                                    'Counts objects with dit strings do not '\n                                    'currently support dit string formatting parameters '\n                                    'creg_sizes or memory_slots')\n                            int_key = int(bitstring.replace(\" \", \"\"), 2)\n                            int_dict[int_key] = value\n                            hex_dict[hex(int_key)] = value\n                        self.hex_raw = hex_dict\n                        self.int_raw = int_dict\n            else:\n                raise TypeError(\"Invalid input key type %s, must be either an int \"\n                                \"key or string key with hexademical value or bit string\")\n        header = {}\n        self.creg_sizes = creg_sizes\n        if self.creg_sizes:\n            header['creg_sizes'] = self.creg_sizes\n        self.memory_slots = memory_slots\n        if self.memory_slots:\n            header['memory_slots'] = self.memory_slots\n        if not bin_data:\n            bin_data = postprocess.format_counts(self.hex_raw, header=header)\n        super().__init__(bin_data)\n        self.time_taken = time_taken\n\n    def most_frequent(self):\n        \"\"\"Return the most frequent count\n\n        Returns:\n            str: The bit string for the most frequent result\n        Raises:\n            QiskitError: when there is >1 count with the same max counts, or\n                an empty object.\n        \"\"\"\n        if not self:\n            raise exceptions.QiskitError(\n                \"Can not return a most frequent count on an empty object\")\n        max_value = max(self.values())\n        max_values_counts = [x[0] for x in self.items() if x[1] == max_value]\n        if len(max_values_counts) != 1:\n            raise exceptions.QiskitError(\n                \"Multiple values have the same maximum counts: %s\" %\n                ','.join(max_values_counts))\n        return max_values_counts[0]\n\n    def hex_outcomes(self):\n        \"\"\"Return a counts dictionary with hexademical string keys\n\n        Returns:\n            dict: A dictionary with the keys as hexadecimal strings instead of\n                bitstrings\n        Raises:\n            QiskitError: If the Counts object contains counts for dit strings\n        \"\"\"\n        if self.hex_raw:\n            return {key.lower(): value for key, value in self.hex_raw.items()}\n        else:\n            bitstring_regex = re.compile(r'^[01\\s]+$')\n            out_dict = {}\n            for bitstring, value in self.items():\n                if not bitstring_regex.search(bitstring):\n                    raise exceptions.QiskitError(\n                        'Counts objects with dit strings do not '\n                        'currently support conversion to hexadecimal')\n                int_key = int(bitstring.replace(\" \", \"\"), 2)\n                out_dict[hex(int_key)] = value\n            return out_dict\n\n    def int_outcomes(self):\n        \"\"\"Build a counts dictionary with integer keys instead of count strings\n\n        Returns:\n            dict: A dictionary with the keys as integers instead of bitstrings\n        Raises:\n            QiskitError: If the Counts object contains counts for dit strings\n        \"\"\"\n        if self.int_raw:\n            return self.int_raw\n        else:\n            bitstring_regex = re.compile(r'^[01\\s]+$')\n            out_dict = {}\n            for bitstring, value in self.items():\n                if not bitstring_regex.search(bitstring):\n                    raise exceptions.QiskitError(\n                        'Counts objects with dit strings do not '\n                        'currently support conversion to integer')\n                int_key = int(bitstring.replace(\" \", \"\"), 2)\n                out_dict[int_key] = value\n            return out_dict\n", "path": "qiskit/result/counts.py"}]}