c# – Replacing all keys found in a dictionary for its value in a list

I have a file that is written DOS format and I need to replace some characters into others. I created a dictionary for that purposes, and now I have to read everyline from my stream and replace my values as I go.

I created this piece of code in C#, however, I highly doubt that this is the way to go, since I figure that C# dictionary class must have a simpler way to this probably common operation. Any feedback is greatly appreciated !

public List<string> ReplaceSpecialCharacters(List<string> lines)
    {
        var result = new List<string>();

        foreach (var line in lines)
        {
            string newLine = string.Empty;

            foreach (var @char in line)
            {
                string replacedChar = @char.ToString();
                bool keyFound = false;

                foreach (var entry in Chars)
                {
                    if (keyFound)
                        continue;

                    if (@char == entry.Key)
                    {
                        replacedChar = entry.Value;
                        keyFound = true;
                    }
                }

                newLine += replacedChar;
            }

            result.Add(newLine);
        }

        return result;
    }

turing machines – Expressing functions using the arithmetic dictionary

i have seen in the “logic to cs” class i take – a theorem that states: “every recursive (computable) function $f$ can be expressed using the arithmetic dictionary {$C_0, C_1, f_+(,), f_x(,)$}”

But we didnt prove this theorem because a part of the students didnt take the “computational models” course (i did take it though)

Where can i find a proof for this theorem? Thanks in advance!

python – Using a dictionary template for consistent response structure from an API

There is no need to use deepcopy here. Just have a function that returns a new object when you need it. And while you’re at it, just make the message and the result parameters of that function. Or even all of them:

def json_response(message, result, status="ok", code=0, error=False):
    return {
        "status" : status,
        "code" : code,
        "error" : error,
        "message" : message,
        "result" : result
    }

@route('/example')
def example():
    result = {
        "title" : "Test Title",
        "body" : "<p>Lorem ipsum dolor sit amet...</p>"
    }
    return json_response("Success", result)

Having all as parameters, but with default values, allows you to do this in the future:

json_response("Failure", None, status="fail", code=404, error=True)

In the end it depends on how often you need to use this template whether or not this is better than just directly returning the dictionary explicitly:

@route('/example')
def example():
    return {
        "status" : "ok",
        "code" : 0,
        "error" : False,
        "message" : "Success",
        "result" : {
            "title" : "Test Title",
            "body" : "<p>Lorem ipsum dolor sit amet...</p>"
        }
    }

Better way to extract html table to dictionary using beautifulsoup in python

I am scrapping html pages. Part of the page has a table which has acts and sections of those acts mentioned in table format. For some other project I need to convert them to Dictionary. The key values are previously set (in the other project). I want to use the same key values for the dictionary and then replace corresponding sections with each new input. The code I have designed works but I am looking for better way to write it. Presently the code looks quite lengthy. The code:

from bs4 import BeautifulSoup as bs, NavigableString

openFile = open('/some path/samplePage.html')
soup = bs(openFile, 'html.parser')

acts = soup.select('#act_table td:nth-of-type(1)')
sections = soup.select('#act_table td:nth-of-type(2)')
dictionary = {}


ipc = 'indian penal code'
poa = 'prevention of atrocities'
pcso = 'protection of children from sexual'
pcr = 'protection of civil rights'


if len(acts) < 1:
    print('no act mentioned')
elif len(acts) < 2:
    act1 = tuple(acts(0).contents)
    sections1 = tuple(sections(0).contents)
elif len(acts) < 3:
    act1 = tuple(acts(0).contents)
    sections1 = tuple(sections(0).contents)
    act2 = tuple(acts(1).contents)
    sections2 = tuple(sections(1).contents)
elif len(acts) < 4:
    act1 = tuple(acts(0).contents)
    sections1 = tuple(sections(0).contents)
    act2 = tuple(acts(1).contents)
    sections2 = tuple(sections(1).contents)
    act3 = tuple(acts(2).contents)
    sections3 = tuple(sections(2).contents)
elif len(acts) < 5:
    act1 = tuple(acts(0).contents)
    sections1 = tuple(sections(0).contents)
    act2 = tuple(acts(1).contents)
    sections2 = tuple(sections(1).contents)
    act3 = tuple(acts(2).contents)
    sections3 = tuple(sections(2).contents)
    act4 = tuple(acts(3).contents)
    sections4 = tuple(sections(3).contents)
else:
    act1 = tuple(acts(0).contents)
    sections1 = tuple(sections(0).contents)
    act2 = tuple(acts(1).contents)
    sections2 = tuple(sections(1).contents)
    act3 = tuple(acts(2).contents)
    sections3 = tuple(sections(2).contents)
    act4 = tuple(acts(3).contents)
    sections4 = tuple(sections(3).contents)
    act5 = tuple(acts(4).contents)


if len(acts) == 0:
    pass
# for first act in list
elif len(acts) == 1:
    if ipc in str(act1).lower():
        dictionary('IPC') = sections1
    elif poa in str(act1).lower():
        dictionary('PoA') = sections1
    elif pcso in str(act1).lower():
        dictionary('PCSO') = sections1
    elif pcr in str(act1).lower():
        dictionary('PCR') = sections1
    else:
        dictionary('Any Other Act') = str(act1).lower()
    print(dictionary)

# for 2nd act in list
elif len(acts) == 2:
    if ipc in str(act1).lower():
        dictionary('IPC') = sections1
    elif poa in str(act1).lower():
        dictionary('PoA') = sections1
    elif pcso in str(act1).lower():
        dictionary('PCSO') = sections1
    else:
        dictionary('Any Other Act') = str(act1).lower()
    if ipc in str(act2).lower():
        dictionary('IPC') = sections2
    elif poa in str(act2).lower():
        dictionary('PoA') = sections2
    elif pcso in str(act2).lower():
        dictionary('PCSO') = sections2
    else:
        dictionary('Any Other Act') = act2
    print(dictionary)
# for 3rd act in list
elif len(acts) == 3:
    if ipc in str(act1).lower():
        dictionary('IPC') = sections1
    elif poa in str(act1).lower():
        dictionary('PoA') = sections1
    elif pcso in str(act1).lower():
        dictionary('PCSO') = sections1
    elif pcr in str(act1).lower():
        dictionary('PCR') = sections1
    else:
        dictionary('Any Other Act') = str(act1).lower()
    if ipc in str(act2).lower():
        dictionary('IPC') = sections2
    elif poa in str(act2).lower():
        dictionary('PoA') = sections2
    elif pcso in str(act2).lower():
        dictionary('PCSO') = sections2
    elif pcr in str(act2).lower():
        dictionary('PCR') = sections2
    else:
        dictionary('Any Other Act') = act2
    #for 3rd option
    if ipc in str(act3).lower():
        dictionary('IPC') = sections3
    elif poa in str(act3).lower():
        dictionary('PoA') = sections3
    elif pcso in str(act3).lower():
        dictionary('PCSO') = sections3
    elif pcr in str(act3).lower():
        dictionary('PCR') = sections3
    else:
        dictionary('Any Other Act') = act3
    print(dictionary)
    # for 4th act in list
elif len(acts) == 4:
    if ipc in str(act1).lower():
        dictionary('IPC') = sections1
    elif poa in str(act1).lower():
        dictionary('PoA') = sections1
    elif pcso in str(act1).lower():
        dictionary('PCSO') = sections1
    elif pcr in str(act1).lower():
        dictionary('PCR') = sections1
    else:
        dictionary('Any Other Act') = str(act1).lower()
    if ipc in str(act2).lower():
        dictionary('IPC') = sections2
    elif poa in str(act2).lower():
        dictionary('PoA') = sections2
    elif pcso in str(act2).lower():
        dictionary('PCSO') = sections2
    elif pcr in str(act2).lower():
        dictionary('PCR') = sections2
    else:
        dictionary('Any Other Act') = act2
    # for 3rd option
    if ipc in str(act3).lower():
        dictionary('IPC') = sections3
    elif poa in str(act3).lower():
        dictionary('PoA') = sections3
    elif pcso in str(act3).lower():
        dictionary('PCSO') = sections3
    elif pcr in str(act3).lower():
        dictionary('PCR') = sections3
    else:
        dictionary('Any Other Act') = act3
    # 4th Option
    if ipc in str(act4).lower():
        dictionary('IPC') = sections4
    elif poa in str(act4).lower():
        dictionary('PoA') = sections4
    elif pcso in str(act4).lower():
        dictionary('PCSO') = sections4
    elif pcr in str(act4).lower():
        dictionary('PCR') = sections4
    else:
        dictionary('Any Other Act') = act4
elif len(acts) == 5:
    if ipc in str(act1).lower():
        dictionary('IPC') = sections1
    elif poa in str(act1).lower():
        dictionary('PoA') = sections1
    elif pcso in str(act1).lower():
        dictionary('PCSO') = sections1
    elif pcr in str(act1).lower():
        dictionary('PCR') = sections1
    else:
        dictionary('Any Other Act') = str(act1).lower()
    if ipc in str(act2).lower():
        dictionary('IPC') = sections2
    elif poa in str(act2).lower():
        dictionary('PoA') = sections2
    elif pcso in str(act2).lower():
        dictionary('PCSO') = sections2
    elif pcr in str(act2).lower():
        dictionary('PCR') = sections2
    else:
        dictionary('Any Other Act') = act2
    # for 3rd option
    if ipc in str(act3).lower():
        dictionary('IPC') = sections3
    elif poa in str(act3).lower():
        dictionary('PoA') = sections3
    elif pcso in str(act3).lower():
        dictionary('PCSO') = sections3
    elif pcr in str(act3).lower():
        dictionary('PCR') = sections3
    else:
        dictionary('Any Other Act') = act3
    # 4th Option
    if ipc in str(act4).lower():
        dictionary('IPC') = sections4
    elif poa in str(act4).lower():
        dictionary('PoA') = sections4
    elif pcso in str(act4).lower():
        dictionary('PCSO') = sections4
    elif pcr in str(act4).lower():
        dictionary('PCR') = sections4
    else:
        dictionary('Any Other Act') = act4
print(dictionary)

The HTML code of one of the files is here:

link to the source code

HashMap Implementation (dictionary) in Python

I attempted making a hashmap in python, and it was harder, due to some limitations but this is my version of dictionaries in python. Are there any way to simplify or do the same thing in less code along with tips and tricks?

class HashMap:
    def __init__(self, memory): # refers to the length of the bucket
            self.data = (None) * memory 
            self.memory = memory

    def _hash(self, key):
        hashed_value = 0
        bucket_length = self.memory
        string_length = len(key)
        i = 0
        while i < string_length:
            hashed_value += (ord(key(i)) * i) % bucket_length
            if hashed_value > bucket_length-1:
                hashed_value %= bucket_length-1

            i += 1
        return hashed_value

    def set(self, key, value):
        address = self._hash(key)
        bucket = self.data(address)
        if not bucket:
            self.data(address) = (key, value, None) # None refers to next pointer
        else:
            while bucket(2) != None:
                bucket = bucket(2)
            bucket(2) = (key, value, None)

    def get(self, key):
        address = self._hash(key)
        bucket = self.data(address)
        if bucket:
            while bucket(2) != None or key != bucket(0):
                bucket = bucket(2)
            if bucket:
                return bucket(1)
        raise KeyError

Python – Run a cumulative sum of items in the dictionary

I have the following dictionary:

d = {1: [2.6], 2: [2.4], 3: [2.5333333333333337]}

I try to find a cumulative sum in every dictionary element. I've been thinking about list compression, but this method has worked well for me to work on each element, but not on the previous element, as is the case here

It should be noted that in my case I always have a single item because I used a method to average the values ​​of my items beforehand.

What I'm looking for is the following:

d = {1: [2.6], 2: [5], 3: [7.5333333333333337]}

Kind regards.

Data structures – How high is the spatial complexity of a Python dictionary?

If Python dictionaries are essentially hash tables and the length of the hashes used in the Python dictionary implementation is 32 bits, this means that regardless of the number of key-value pairs that actually exist in a particular dictionary, that Dictionary size is static and fixed with a length of 232.

Such an implementation would be a waste of memory, so I assume that this is not the actual complexity of the space. How is a Python dictionary actually implemented and what is its spatial complexity?

python 3.x – HOW TO INSERT DICTIONARY KEY (CPF) IN ANOTHER DICTIONARY WITH CUSTOMER DATA (NAME, TELEPHONE, etc.).

Write a program that you can use to manage a company's customer database. Customers are stored in a dictionary in which each customer's key is their CPF, and the value is another dictionary with the customer data (name, address, phone, email, preferred).

List elements in a dictionary using enumerate () in Python

As the title suggests, I wanted to list the key and its values ​​(without parentheses) in Python.
I tried the following code:

example_dict = {'left':'<','right':'>','up':'^','down':'v',}
(print(i,j,a) for (i,j,a) in enumerate((example_dict).items()))

But it doesn't work.
I want the output to be like this

0 left <
1 right >
2 up ^
3 down v

Thanks in advance

python 3.x – Add a new pair (key, value) in the nested dictionary – python3

Hello, I have created what I call a nested dictionary:

gradeDict = { 
   "Intro to Programming":{ 
      "student":{ 
         "firstname":"Mike",
         "lastname":"Miller",
         "marks":{ 
            "PS01":70,
            "PS02":80
         }
      }
   }
}
print(gradeDict('Intro to Programming')('student')('marks'))

what after querying the values ​​in key & # 39; markings & # 39; gives the values

{'PS01': 70, 'PS02': 80}

That's perfect. Now I want to add a NEW pair (key, value) to the parent key tags:

gradeDict.update( {"Intro to Programming":{ "student":{ "firstname":"Mike",
         "lastname":"Miller","marks":{ "PS03":10}}}} )

print(gradeDict('Intro to Programming')('student')('marks'))

Unfortunately there is

{'PS03': 10}

what I do not understand, a key should only be overwritten if it already exists, otherwise appended. & # 39; Marks & # 39; exists, & # 39; PS03 & # 39; However not. What am I missing here or how do I get the desired entry:

{'PS01': 70, 'PS02': 80, 'PS03': 10}

Thanks a lot…