Youngin Na - 2 years ago 82

Python Question

`for k, v in sorted(total_prob.items(), key = lambda x: x[1], reverse=True):`

MLE_Prob, Bi_Prob = v

# here, k = tuple type of bigrams. v = tuple type of (mle prob, bi prob)

print tabulate([k,v[0], v[1]], headers = ["Bigram", "MLE_Prob", "Bi_Prob"], tablefmt="grid")

my data consists like, {(a,b) : (c,d)}. and the result I wanna print is

`header1 header2 header3`

(a, b) c d

but I got type error, 'float'object is not iterable.

mle prob and bi prob are both float and its value is usually 0.0022323xxx something like that.

How can dissolve this error?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Firstly you need to create array with your results, and then display it using tabulate. You cannot display row by row, but whole grid at once.

```
from tabulate import tabulate
total_prob = {("a", "b"): (1, 2), ("c", "d"): (3, 4)}
results = []
for k, v in sorted(total_prob.items(), key = lambda x: x[1], reverse=True):
MLE_Prob, Bi_Prob = v
results.append([k,MLE_Prob, Bi_Prob])
print tabulate(results, headers = ["Bigram", "MLE_Prob", "Bi_Prob"], tablefmt="grid")
```

Output:

```
+------------+------------+-----------+
| Bigram | MLE_Prob | Bi_Prob |
+============+============+===========+
| ('c', 'd') | 3 | 4 |
+------------+------------+-----------+
| ('a', 'b') | 1 | 2 |
+------------+------------+-----------+
```

Tabulate takes an array of arrays (array of rows) as first argument. So at least you needed to use tabulate like this: `tabulate([[k,v[0], v[1]]],...`

but then output will be like this:

```
+------------+------------+-----------+
| Bigram | MLE_Prob | Bi_Prob |
+============+============+===========+
| ('c', 'd') | 3 | 4 |
+------------+------------+-----------+
+------------+------------+-----------+
| Bigram | MLE_Prob | Bi_Prob |
+============+============+===========+
| ('a', 'b') | 1 | 2 |
+------------+------------+-----------+
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**