Solved

Allow user to choose items in two Python dictionaries to build a third one

Posted on 2014-04-15
1
189 Views
Last Modified: 2014-04-15
Hi there!

I am trying to build a function that compares fields_csv and fields_db and asks the users which value he's like to import.

I've built it with success with lists but I need both values and keys so i've chosen dictionaries for the job.

I thought something similar and read the subject doing exercises on Code Academy but I still can't get how to handle it:

csv_fields = {'name' : 'john', 'surname' : 'white', 'note' : 'new note'}
db_fields = {'name' : 'john', 'surname' : 'white', 'note' : 'old note'}
import_fields = {}

def fields_check(csv_fields, db_fields):
    for csv_key, csv_value in csv_fields.iteritems():
        for db_key, db_value in db_fields.iteritems():
            if csv_value == db_value:
                import_fields[csv_key] = csv_value
            elif csv_value != db_value:
                while True:
                    print ""
                    print "1) Field in csv: " + csv_value
                    print "2) Field in db: " + db_value
                    print ""
                    user_answer = str(raw_input("Which do you want to keep? [1 o 2]: "))
                    print ""
                    if user_answer == "1":
                        import_fields[csv_key] = csv_value
                        print "You dedided to keep the field name: " + csv_key + " with value: " + csv_value
                        break
                    elif user_answer == "2":
                        import_fields[db_key] = db_value
                        print "You dedided to keep the field name: " + db_key + " with value: " + db_value
                        break
            else:
                print "Error!"

fields_check(csv_fields, db_fields)
print import_fields

Open in new window

0
Comment
Question by:ltpitt
1 Comment
 
LVL 28

Accepted Solution

by:
pepr earned 500 total points
ID: 40002567
I guess that both csv and db should do have the same keys, and only the values may differ. If it is the case then you want to loop through all keys, and it does not matter whether you get them from the csv_fields or the db_fields. Then you get the values for the key from both dictionaries. And then ask the user only when the values differ, as you did.

To summarize, you need only one for loop to go through the keys.
csv_fields = {'name' : 'john', 'surname' : 'white', 'note' : 'new note'}
db_fields = {'name' : 'john', 'surname' : 'white', 'note' : 'old note'}
import_fields = {}

def fields_check(csv_fields, db_fields):
    for k in csv_fields:
        csv_value = csv_fields[k]
        db_value = db_fields[k]
        if csv_value == db_value:
            import_fields[k] = csv_value
        elif csv_value != db_value:
            while True:
                print "The key is:", k
                print
                print "1) Field in csv:", csv_value
                print "2) Field in db: ", db_value
                print
                user_answer = raw_input("Which do you want to keep? [1 o 2]: ")
                print
                if user_answer == "1":
                    import_fields[k] = csv_value
                    print "You dedided to keep the field name:", k, 
                    print "with value:", csv_value
                    break
                elif user_answer == "2":
                    import_fields[k] = db_value
                    print "You dedided to keep the field name:", k, "with value:", db_value
                    break
                else:
                    print "Error!"


fields_check(csv_fields, db_fields)
print import_fields

Open in new window

The csv_value can be extracted via .iteritems() as you did in your code to remove the next line. I did not do that to emphasise symmetry.

If the keys may differ in boh dictionaries, it is possible to iterate through the unified set of the keys from both dictionaries. In this case, the value must be extracted via:
    csv_value = csv_fields.get(k, None)

Open in new window

where None is the default value if the key is not in the dictionary.

It is usually better to use the print command with arguments separated by commas. The reason is that if the argument is not a string, it is converted to the string representation automatically by the print. On the other hand the plus operator needs the strings on both sides.

The raw_input() result need not to be converted to str because it already is str.

If the print command is too long, you can spit it to two prints where the first one ends with the trailing comma -- as shown when printing the csv choice. The comma in print adds the separating space automatically.
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Plenty of writing has gone on the web trying to compare Python with other competitive programming languages and vice versa. However, not much has been put into a wholistic perspective. This article should help you decide whether to adopt Python as a…
Installing Python 2.7.3 version on Windows operating system For installing Python first we need to download Python's latest version from URL" www.python.org " You can also get information on Python scripting language from the above mentioned we…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now