How to display python dict in html table - python-2.7

I have some data stored in a python dict and need to display it in a particular order in html. For example;
values = {
server1 : {'key1' : 'b', 'key2' : 'd'},
server2 : {'key1' : 'e', 'key2' : 'f'},
server3 : {'key1' : 'g', 'key2' : 'h'},
server4 : {'key1' : 'i', 'key2' : 'j'},
server5 : {'key1' : 'k', 'key2' : 'l'},
server6 : {'key1' : 'm', 'key2' : 'n'},
}
should be displayed as:
Thanks

Welcome to StackOverflow! Hope this helps,.
In your input, you need to ensure that there are single quotes around the keys('server1', 'server2',.... ). Otherwise, you can build your dictionary in Python.
>>> values = {
... 'server1' : {'key1' : 'b', 'key2' : 'd'},
... 'server2' : {'key1' : 'e', 'key2' : 'f'},
... 'server3' : {'key1' : 'g', 'key2' : 'h'},
... 'server4' : {'key1' : 'i', 'key2' : 'j'},
... 'server5' : {'key1' : 'k', 'key2' : 'l'},
... 'server6' : {'key1' : 'm', 'key2' : 'n'},
... }
>>>
>>> df = pd.DataFrame(values)
>>> df
server1 server2 server3 server4 server5 server6
key1 b e g i k m
key2 d f h j l n
To conver to HTML format
>>> df.to_html()
'<table border="1" class="dataframe">\n <thead>\n <tr style="text-align: right;">\n <th></th>\n <th>server1</th>\n <th>server2</th>\n <th>server3</th>\n <th>server4</th>\n <th>server5</th>\n <th>server6</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>key1</th>\n <td>b</td>\n <td>e</td>\n <td>g</td>\n <td>i</td>\n <td>k</td>\n <td>m</td>\n </tr>\n <tr>\n <th>key2</th>\n <td>d</td>\n <td>f</td>\n <td>h</td>\n <td>j</td>\n <td>l</td>\n <td>n</td>\n </tr>\n </tbody>\n</table>'
>>>
Using pandas to_html, you can get your HTML data.

Related

How can I i get the same result as shown on the docstring

def make_str_from_row(board, row_index):
""" (list of list of str, int) -> str
Return the characters from the row of the board with index row_index
as a single string.
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1)
'XSOB'
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B'], ['F', 'G', 'O', 'L']], 2)
'FGOL'
"""
Use str.join:
def make_str_from_row(board, row_index):
"""(list of list of str, int) -> str
Return the characters from the row of the board with index row_index
as a single string.
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1)
'XSOB'
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B'], ['F', 'G', 'O', 'L']], 2)
'FGOL'
"""
return "".join(board[row_index])
print(make_str_from_row([["A", "N", "T", "T"], ["X", "S", "O", "B"]], 0))
print(make_str_from_row([["A", "N", "T", "T"], ["X", "S", "O", "B"]], 1))
print(
make_str_from_row(
[["A", "N", "T", "T"], ["X", "S", "O", "B"], ["F", "G", "O", "L"]], 2
)
)
Prints:
ANTT
XSOB
FGOL

How to compare elements of nested lists between each other?

I try to compare elements of nested list between each other. Let's say I have the following list:
list1 = [['v1', '1', '2'],['v1', '2', '2'], ['v2', '1'], ['v3'], ['v4', '1'], ['v4', '2']]
and I would like to reach to:
result = [['v1', '2'],['v1', '2'],['v2', '1'], ['v3'], ['v4'], ['v4']]
I've done a small code, but it does not look to work very well.
for i in range(1, len(list1) - 1):
previousone = list1[i-1]
currentone = list1[i]
nextone = list1[i+1]
lenprevious = len(previousone)
lencurrent = len(currentone)
lennext = len(nextone)
minlen = min(lenprevious,lencurrent,lennext) -1
common = ''
for j in range(minlen):
if j == 0:
if previousone[j] == currentone[j]:
common += str(previousone[j])
if previousone[j] != currentone[j]:
if currentone[j] == nextone[j]:
common += str(currentone[j])
else:
common += currentone
break
else:
if common != '':
if previousone[j] == currentone[j]:
common.join('_',str(nextone[j]))
else:
if currentone[j] == nextone[j]:
common.join('_',str(nextone[j]))
else:
break
else:
break
print common
result.append(common)
The idea, is to compare the 1st element of the sub-list vs the 1st element of the previous sub-list. If no match, then we compare with the next sub-list. If no match, we get in common the 1st element of the current sub-list.
Then, if it's matching, we do the same for the next element of the sub-list and so one until the last one. In the end, I want to have in common, a list of the common elements if any, if not I want the current sub-list.
Does anyone has any idea how to make it work? Thanks in advance!
EDIT ::
The logic would be:
Iteration 1 -> Previous : ['v1', '1', '2'] and Current : ['v1', '2', '2'] and Next : ['v2', '1']
We compare each element from each list.
First, we compare the Previous and the Current.
First element of those lists are 'v1', so we append 'v1' in result and we go to the next element, here '1' and '2'.
They are not the same so we pass until the next element, which are '2' and '2': identical.
We append in result to get Result :
[['v1', '2'], ['v1', '2'], [], [], [], []]
Iteration 2 -> Previous : ['v1', '2', '2'] and Current : ['v2', '1'] and Next : ['v3']
First we compare Previous and Current. 'v1' different from 'v2'.
So we compare Current and Next. 'v2' different from 'v3'.
So we append in result the current and we get:
[['v1', '2'], ['v1', '2'], ['v2', '1'], [], [], []]
Iteration 3 -> Previous : ['v2', '1'] and Current : ['v3'] and Next : ['v4', '1']
Same as above, 'v2' different from 'v3' and 'v3' different from 'v4' so we append the current and get:
[['v1', '2'], ['v1', '2'], ['v2', '1'], ['v3'], [], []]
Iteration 4 -> Previous : ['v3'] and Current : ['v4', '1'] and Next: ['v4', '2']
'v3' different from 'v4' so we compare Current and Next: 'v4' is common so we append 'v4':
[['v1', '2'], ['v1', '2'], ['v2', '1'], ['v3'], ['v4'], []]
Iteration 5 -> Previous : ['v4', '1'] and Current : ['v4', '2'] and Next : ??
'v4' is common so we append 'v4' and get the final result:
Result: [['v1', '2'], ['v1', '2'], ['v2', '1'], ['v3'], ['v4'], ['v4']]
But I do not know how to reach there..
Below is the implementation according to your desired result,
Core Logic
def intersection(lst1, lst2):
return list(set(lst1) & set(lst2))
list1 = [['v1', '1', '2'],['v1', '2', '2'], ['v2', '1'], ['v3'], ['v4', '1'], ['v4', '2']]
result = []
list_len = len(list1)
if list_len == 0:
pass
elif list_len == 1:
result.append(list1)
else:
for i in range(list_len):
if i == 0:
current = list1[i]
next = list1[i+1]
print("Iteration {} -> Previous : No previous available Current : {} Next: {}".format(i, current, next))
if current[0] == next[0]:
result.append(intersection(current, next))
else:
result.append(current)
elif i == list_len - 1:
previous = list1[i-1]
current = list1[i]
print("Iteration {} -> Previous : {} Current : {} Next: No next available".format(i, previous, current))
if current[0] != previous[0]:
result.append(current)
else:
result.append(intersection(current, previous))
else:
previous = list1[i-1]
current = list1[i]
next = list1[i+1]
print("Iteration {} -> Previous : {} Current : {} Next: {}".format(i, previous, current, next))
if current[0] == previous[0]:
result.append(intersection(current, previous))
else:
if current[0] == next[0]:
result.append(intersection(current, next))
else:
result.append(current)
print("Result : {}".format(result))
Output
Iteration 0 -> Previous : No previous available Current : ['v1', '1', '2'] Next: ['v1', '2', '2']
Iteration 1 -> Previous : ['v1', '1', '2'] Current : ['v1', '2', '2'] Next: ['v2', '1']
Iteration 2 -> Previous : ['v1', '2', '2'] Current : ['v2', '1'] Next: ['v3']
Iteration 3 -> Previous : ['v2', '1'] Current : ['v3'] Next: ['v4', '1']
Iteration 4 -> Previous : ['v3'] Current : ['v4', '1'] Next: ['v4', '2']
Iteration 5 -> Previous : ['v4', '1'] Current : ['v4', '2'] Next: No next available
Result : [['v1', '2'], ['v1', '2'], ['v2', '1'], ['v3'], ['v4'], ['v4']]

How to merge list of dict with same keys?

I have a list:
list=[{'Query': 'documents'}, {'entity': 'a'}, {'value': 'b'}, {'entity': 'c'}, {'value': 'd'}, {'records':21}]
I want following o/p:
d={'Query': ['documents'],'entity': ['a','c'],'value': ['b','d'],'records':[21]}
try this code :
list=[{'Query': 'documents'}, {'entity': 'a'}, {'value': 'b'}, {'entity': 'c'}, {'value': 'd'}, {'records':21}]
d={}
for i in list :
for j,k in i.items():
l = []
if j in d:
l = d[j]
l.append(k)
d[j] = l
else:
l.append(str(k))
d[j]=l
print(d)
output:
{'records': ['21'], 'value': ['b', 'd'], 'entity': ['a', 'c'], 'Query': ['documents']}

Find element in a nested list and transform (groovy)

If I have a Groovy nested list such as:
List list = ['a', 'b', 'c', ['d', 'e', ['f']]]
I would like to be able to search the list for a particular element, say 'd' and then transform that element to something else such as ['g', 'h'] so that the new list looks like:
['a', 'b', 'c', [['g', 'h'], 'e', ['f']]]
Like this??
List list = ['a', 'b', 'c', ['d', 'e', ['f']]]
assert list.collectNested{
if (it == 'd') {
['g', 'h']
} else {
it
}
} == ['a', 'b', 'c', [['g', 'h'], 'e', ['f']]]
Use following generic approach :-
def findAndReplace(def listValue, def listIndex, def valueToCompare, def valueToReplace, def originalList) {
if(listValue instanceof List) {
listValue.eachWithIndex { insideListValue, insideListIndex ->
findAndReplace(insideListValue, insideListIndex, valueToCompare, valueToReplace, listValue)
}
}else if(listValue == valueToCompare) {
originalList[listIndex] = valueToReplace
}
}
List originalList = ['a', 'b', 'c', ['d', 'e', ['f']]]
def valueToCompare = 'd'
def valueToReplace = ['g', 'h']
originalList.eachWithIndex { listValue, listIndex ->
findAndReplace(listValue, listIndex, valueToCompare, valueToReplace, originalList)
}
println originalList
Output: [a, b, c, [[g, h], e, [f]]]
Hope it will help you...:)

Invalid cell coordinate phpExcel

I have tested that if using vlookup to search in the self sheet "=vlookup(h2, A2:B2000, 2, False)" and returning value from other sheet "=SupplierList!A2" and "=vlookup(SupplierList!H3, A2:B2000, 2, False)" are also fine.
so why only "=vlookup(h3, SupplierList!A2:B2000, 2, False)" drives into error?
--------------------------- ERROR MESSAGE -------------------------------
Fatal error: Uncaught exception 'Exception' with message 'PO!G2 -> Invalid cell coordinate A' in C:\Program Files\EasyPHP-5.3.6.0\www\ExcelImporter\Classes\PHPExcel\Cell.php:288 Stack trace: #0 C:\Program Files\EasyPHP-5.3.6.0\www\ExcelImporter\Classes\PHPExcel\Cell.php(204): PHPExcel_Cell->getCalculatedValue() #1 C:\Program Files\EasyPHP-5.3.6.0\www\ExcelImporter\Documentation\Examples\index.php(36): PHPExcel_Cell->getFormattedValue() #2 {main} thrown in C:\Program Files\EasyPHP-5.3.6.0\www\ExcelImporter\Classes\PHPExcel\Cell.php on line 288
--------------------------- ERROR MESSAGE -------------------------------
The Cell is with formula like this
**=IF(ISERROR(VLOOKUP(H2349,'Supplier List'!A:B,2,FALSE)),"-",VLOOKUP(H2349,'Supplier List'!A:B,2,FALSE))**
Too long to be a comment...
When debugging calculation errors, I use the following:
function testFormula($sheet,$cell) {
$formulaValue = $sheet->getCell($cell)->getValue();
echo '<b>'.$cell.' Value is </b>'.$formulaValue."<br />\n";
$expectedValue = $sheet->getCell($cell)->getOldCalculatedValue();
echo '<b>'.$cell.' Expected Value is </b>'.((!is_null($expectedValue)) ? $expectedValue : 'UNKNOWN')."<br />\n";
$calculate = false;
try {
$tokens = PHPExcel_Calculation::getInstance()->parseFormula($formulaValue,$sheet->getCell($cell));
echo '<b>Parser Stack :-</b><pre>';
print_r($tokens);
echo '</pre>';
$calculate = true;
} catch (Exception $e) {
echo "PARSER ERROR: ".$e->getMessage()."<br />\n";
echo '<b>Parser Stack :-</b><pre>';
print_r($tokens);
echo '</pre>';
}
if ($calculate) {
try {
$cellValue = $sheet->getCell($cell)->getCalculatedValue();
echo '<b>'.$cell.' Calculated Value is </b>'.$cellValue."<br />\n";
echo '<h3>Evaluation Log:</h3><pre>';
print_r(PHPExcel_Calculation::getInstance()->debugLog);
echo '</pre>';
} catch (Exception $e) {
echo "CALCULATION ENGINE ERROR: ".$e->getMessage()."<br />\n";
echo '<h3>Evaluation Log:</h3><pre>';
print_r(PHPExcel_Calculation::getInstance()->debugLog);
echo '</pre>';
}
}
}
$sheet = $objPHPExcel->getActiveSheet();
PHPExcel_Calculation::getInstance()->writeDebugLog = true;
testFormula($sheet,'A4');
This provides a fairly detailed log of everything that the calculation engine is doing, allowing the cause of the problem to be identified.
If you simply want to disable cell value calculation when saving a file, then you can issue the following command after instantiating yor writer, but before issuing the save command:
$objWriter->setPreCalculateFormulas(FALSE);
para resolver esse problema "Invalid cell coordinate" $this->caracteres = array(
' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'W', 'Z',
'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM',
'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AX', 'AY', 'AW', 'AZ');
adicione mais caracteres ,
'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM',
'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AX', 'AY', 'AW', 'AZ'); ....
English
to solve this problem "Invalid cell coordinate" $ this-> characters = array (
             '', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L' , 'M',
             'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'W', 'Z '
             'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM '
             'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AX', 'AY', 'AW', 'AZ ');
add more characters,
             'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM '
             'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AX', 'AY', 'AW', 'AZ '); ....